Class ActiveRecord::Base
In: lib/active_record/base.rb
lib/active_record/connection_adapters/abstract/connection_specification.rb
lib/active_record/connection_adapters/db2_adapter.rb
lib/active_record/connection_adapters/mysql_adapter.rb
lib/active_record/connection_adapters/oci_adapter.rb
lib/active_record/connection_adapters/postgresql_adapter.rb
lib/active_record/connection_adapters/sqlite_adapter.rb
lib/active_record/connection_adapters/sqlserver_adapter.rb
lib/active_record/deprecated_finders.rb
lib/active_record/locking.rb
lib/active_record/query_cache.rb
lib/active_record/timestamp.rb
Parent: Object

The root class of all active record objects.

Methods

==   ===   []   []=   attr_accessible   attr_protected   attribute_names   attribute_present?   attributes   attributes=   attributes_before_type_cast   attributes_with_quotes_pre_oci   benchmark   class_name_of_active_record_descendant   clone   column_for_attribute   column_methods_hash   column_names   columns   columns_hash   compute_type   connected?   connection   connection   connection=   connection=   constrain   content_columns   count   count_by_sql   create   decrement   decrement!   decrement_counter   delete   delete_all   destroy   destroy   destroy_all   encode_quoted_value   eql?   establish_connection   exists?   extract_options_from_args!   find   find_by_sql   freeze   frozen?   hash   id   id=   increment   increment!   increment_counter   inheritance_column   new   new_record?   primary_key   quote_bound_value   raise_if_bind_arity_mismatch   read_methods   readonly!   readonly?   reload   remove_connection   replace_bind_variables   replace_named_bind_variables   reset_column_information   reset_primary_key   reset_subclasses   reset_table_name   respond_to?   sanitize_sql   save   scope_constraints   scope_constraints=   sequence_name   serialize   serialized_attributes   set_inheritance_column   set_primary_key   set_sequence_name   set_table_name   silence   subclasses   table_name   threaded_connections   threaded_connections=   to_param   toggle   toggle!   update   update_all   update_attribute   update_attributes   validate_find_options  

External Aliases

set_table_name -> table_name=
set_primary_key -> primary_key=
set_inheritance_column -> inheritance_column=
set_sequence_name -> sequence_name=
scope_constraints -> scope_constrains
  backwards compatibility
scope_constraints= -> scope_constrains=
  backwards compatibility
sanitize_sql -> sanitize_conditions
respond_to? -> respond_to_without_attributes?
  For checking respond_to? without searching the attributes (which is faster).
connection= -> connection_without_query_cache=

Public Class methods

Overwrite the default class equality method to provide support for association proxies.

If this macro is used, only those attributes named in it will be accessible for mass-assignment, such as new(attributes) and attributes=(attributes). This is the more conservative choice for mass-assignment protection. If you’d rather start from an all-open default and restrict attributes as needed, have a look at attr_protected.

Attributes named in this macro are protected from mass-assignment, such as new(attributes) and attributes=(attributes). Their assignment will simply be ignored. Instead, you can use the direct writer methods to do assignment. This is meant to protect sensitive attributes from being overwritten by URL/form hackers. Example:

  class Customer < ActiveRecord::Base
    attr_protected :credit_rating
  end

  customer = Customer.new("name" => David, "credit_rating" => "Excellent")
  customer.credit_rating # => nil
  customer.attributes = { "description" => "Jolly fellow", "credit_rating" => "Superb" }
  customer.credit_rating # => nil

  customer.credit_rating = "Average"
  customer.credit_rating # => "Average"

Log and benchmark multiple statements in a single block. Example:

  Project.benchmark("Creating project") do
    project = Project.create("name" => "stuff")
    project.create_manager("name" => "David")
    project.milestones << Milestone.find(:all)
  end

The benchmark is only recorded if the current level of the logger matches the log_level, which makes it easy to include benchmarking statements in production software that will remain inexpensive because the benchmark will only be conducted if the log level is low enough.

The logging of the multiple statements is turned off unless use_silence is set to false.

Returns a hash of all the methods added to query each of the columns in the table with the name of the method as the key and true as the value. This makes it possible to do O(1) lookups in respond_to? to check if a given method for attribute is available.

Returns an array of column objects for the table associated with this class.

Returns an array of column objects for the table associated with this class.

Returns true if a connection that’s accessible to this class have already been opened.

Returns the connection currently associated with the class. This can also be used to "borrow" the connection to do database work unrelated to any of the specific Active Records.

Set the connection for the class.

Add constraints to all queries to the same model in the given block. Currently supported constraints are :conditions and :joins

  Article.constrain(:conditions => "blog_id = 1") do
    Article.find(1) # => SELECT * from articles WHERE blog_id = 1 AND id = 1
  end

Returns an array of column objects where the primary id, all columns ending in "_id" or "_count", and columns used for single table inheritance have been removed.

Returns the number of records that meet the conditions. Zero is returned if no records match. Example:

  Product.count "sales > 1"

Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.

  Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"

Creates an object, instantly saves it as a record (if the validation permits it), and returns it. If the save fails under validations, the unsaved object is still returned.

Works like increment_counter, but decrements instead.

Deletes the record with the given id without instantiating an object first. If an array of ids is provided, all of them are deleted.

Deletes all the records that match the condition without instantiating the objects first (and hence not calling the destroy method). Example:

  Post.destroy_all "person_id = 5 AND (category = 'Something' OR category = 'Else')"

Destroys the record with the given id by instantiating the object and calling destroy (all the callbacks are the triggered). If an array of ids is provided, all of them are destroyed.

Destroys the objects for all the records that match the condition by instantiating each object and calling the destroy method. Example:

  Person.destroy_all "last_login < '2004-04-04'"

Establishes the connection to the database. Accepts a hash as input where the :adapter key must be specified with the name of a database adapter (in lower-case) example for regular databases (MySQL, Postgresql, etc):

  ActiveRecord::Base.establish_connection(
    :adapter  => "mysql",
    :host     => "localhost",
    :username => "myuser",
    :password => "mypass",
    :database => "somedatabase"
  )

Example for SQLite database:

  ActiveRecord::Base.establish_connection(
    :adapter => "sqlite",
    :dbfile  => "path/to/dbfile"
  )

Also accepts keys as strings (for parsing from yaml for example):

  ActiveRecord::Base.establish_connection(
    "adapter" => "sqlite",
    "dbfile"  => "path/to/dbfile"
  )

The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError may be returned on an error.

Returns true if the given id represents the primary key of a record in the database, false otherwise. Example:

  Person.exists?(5)

Find operates with three different retrieval approaches:

  • Find by id: This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]). If no record can be found for all of the listed ids, then RecordNotFound will be raised.
  • Find first: This will return the first record matched by the options used. These options can either be specific conditions or merely an order. If no record can matched, nil is returned.
  • Find all: This will return all the records matched by the options used. If no records are found, an empty array is returned.

All approaches accept an option hash as their last parameter. The options are:

  • :conditions: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro.
  • :order: An SQL fragment like "created_at DESC, name".
  • :limit: An integer determining the limit on the number of rows that should be returned.
  • :offset: An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
  • :joins: An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed). The records will be returned read-only since they will have attributes that do not correspond to the table’s columns. Use find_by_sql to circumvent this limitation.
  • :include: Names associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer to already defined associations. See eager loading under Associations.
  • :select: By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join, but not include the joined columns.
  • :readonly: Mark the returned records read-only so they cannot be saved or updated.

Examples for find by id:

  Person.find(1)       # returns the object for ID = 1
  Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
  Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
  Person.find([1])     # returns an array for objects the object with ID = 1
  Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")

Examples for find first:

  Person.find(:first) # returns the first object fetched by SELECT * FROM people
  Person.find(:first, :conditions => [ "user_name = ?", user_name])
  Person.find(:first, :order => "created_on DESC", :offset => 5)

Examples for find all:

  Person.find(:all) # returns an array of objects for all the rows fetched by SELECT * FROM people
  Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50)
  Person.find(:all, :offset => 10, :limit => 10)
  Person.find(:all, :include => [ :account, :friends ])

Works like find(:all), but requires a complete SQL string. Examples:

  Post.find_by_sql "SELECT p.*, c.author FROM posts p, comments c WHERE p.id = c.post_id"
  Post.find_by_sql ["SELECT * FROM posts WHERE author = ? AND created > ?", author_id, start_date]

Increments the specified counter by one. So DiscussionBoard.increment_counter("post_count", discussion_board_id) would increment the "post_count" counter on the board responding to discussion_board_id. This is used for caching aggregate values, so that they don’t need to be computed every time. Especially important for looping over a collection where each element require a number of aggregate values. Like the DiscussionBoard that needs to list both the number of posts and comments.

Defines the column name for use with single table inheritance — can be overridden in subclasses.

New objects can be instantiated as either empty (pass no construction parameter) or pre-set with attributes but not yet saved (pass a hash with key names matching the associated table column names). In both instances, valid attribute keys are determined by the column names of the associated table — hence you can’t have attributes that aren’t part of the table columns.

Defines the primary key field — can be overridden in subclasses. Overwriting will negate any effect of the primary_key_prefix_type setting, though.

Contains the names of the generated reader methods.

Remove the connection for this class. This will close the active connection and the defined connection (if they exist). The result can be used as argument for establish_connection, for easy re-establishing of the connection.

Resets all the cached information about columns, which will cause them to be reloaded on the next request.

Specifies that the attribute by the name of attr_name should be serialized before saving to the database and unserialized after loading from the database. The serialization is done through YAML. If class_name is specified, the serialized object must be of that class on retrieval or SerializationTypeMismatch will be raised.

Returns a hash of all the attributes that have been specified for serialization as keys and their class restriction as values.

Sets the name of the inheritance column to use to the given value, or (if the value # is nil or false) to the value returned by the given block.

Example:

  class Project < ActiveRecord::Base
    set_inheritance_column do
      original_inheritance_column + "_id"
    end
  end

Sets the name of the primary key column to use to the given value, or (if the value is nil or false) to the value returned by the given block.

Example:

  class Project < ActiveRecord::Base
    set_primary_key "sysid"
  end

Sets the name of the sequence to use when generating ids to the given value, or (if the value is nil or false) to the value returned by the given block. This is required for Oracle and is useful for any database which relies on sequences for primary key generation.

Setting the sequence name when using other dbs will have no effect. If a sequence name is not explicitly set when using Oracle, it will default to the commonly used pattern of: #{table_name}_seq

Example:

  class Project < ActiveRecord::Base
    set_sequence_name "projectseq"   # default would have been "project_seq"
  end

Sets the table name to use to the given value, or (if the value is nil or false) to the value returned by the given block.

Example:

  class Project < ActiveRecord::Base
    set_table_name "project"
  end

Silences the logger for the duration of the block.

Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending directly from ActiveRecord. So if the hierarchy looks like: Reply < Message < ActiveRecord, then Message is used to guess the table name from even when called on Reply. The rules used to do the guess are handled by the Inflector class in Active Support, which knows almost all common English inflections (report a bug if your inflection isn’t covered).

Additionally, the class-level table_name_prefix is prepended to the table_name and the table_name_suffix is appended. So if you have "myapp_" as a prefix, the table name guess for an Account class becomes "myapp_accounts".

You can also overwrite this class method to allow for unguessable links, such as a Mouse class with a link to a "mice" table. Example:

  class Mouse < ActiveRecord::Base
     set_table_name "mice"
  end

Finds the record from the passed id, instantly saves it with the passed attributes (if the validation permits it), and returns it. If the save fails under validations, the unsaved object is still returned.

Updates all records with the SET-part of an SQL update statement in updates and returns an integer with the number of rows updated. A subset of the records can be selected by specifying conditions. Example:

  Billing.update_all "category = 'authorized', approved = 1", "author = 'David'"

Protected Class methods

Returns the name of the class descending directly from ActiveRecord in the inheritance hierarchy.

Returns the class type of the record using the current module as a prefix. So descendents of MyApp::Business::Account would appear as MyApp::Business::AccountSubclass.

Accepts an array or string. The string is returned untouched, but the array has each value sanitized and interpolated into the sql statement.

  ["name='%s' and group_id='%s'", "foo'bar", 4]  returns  "name='foo''bar' and group_id='4'"

Public Instance methods

Returns true if the comparison_object is the same object, or is of the same type and has the same id.

Returns the value of the attribute identified by attr_name after it has been typecast (for example, "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)). (Alias for the protected read_attribute method).

Updates the attribute identified by attr_name with the specified value. (Alias for the protected write_attribute method).

Returns an array of names for the attributes available on this object sorted alphabetically.

Returns true if the specified attribute has been set by the user or by a database load and is neither nil nor empty? (the latter only applies to objects that respond to empty?, most notably Strings).

Returns a hash of all the attributes with their names as keys and clones of their objects as values.

Allows you to set all the attributes at once by passing in a hash with keys matching the attribute names (which again matches the column names). Sensitive attributes can be protected from this form of mass-assignment by using the attr_protected macro. Or you can alternatively specify which attributes can be accessed in with the attr_accessible macro. Then all the attributes not included in that won’t be allowed to be mass-assigned.

Returns a hash of cloned attributes before typecasting and deserialization.

attributes_with_quotes_pre_oci(include_primary_key = true)

Alias for attributes_with_quotes

Returns a clone of the record that hasn’t been assigned an id yet and is treated as a new record.

Returns the column object for the named attribute.

Returns the connection currently associated with the class. This can also be used to "borrow" the connection to do database work that isn’t easily done without going straight to SQL.

Initializes the attribute to zero if nil and subtracts one. Only makes sense for number-based attributes. Returns self.

Decrements the attribute and saves the record.

Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can’t be persisted).

Just freeze the attributes hash, such that associations are still accessible even on destroyed records.

Delegates to id in order to allow two records of the same type and id to work with something like:

  [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]

Every Active Record class must use "id" as their primary ID. This getter overwrites the native id method, which isn’t being used in this context.

Sets the primary ID.

Initializes the attribute to zero if nil and adds one. Only makes sense for number-based attributes. Returns self.

Increments the attribute and saves the record.

Returns true if this object hasn’t been saved yet — that is, a record for the object doesn’t exist yet.

Reloads the attributes of this object from the database.

A Person object with a name attribute can ask person.respond_to?("name"), person.respond_to?("name="), and person.respond_to?("name?") which will all return true.

  • No record exists: Creates a new record with values matching those of the object attributes.
  • A record does exist: Updates the record with values matching those of the object attributes.
to_param()

Alias for id

Turns an attribute that’s currently true into false and vice versa. Returns self.

Toggles the attribute and saves the record.

Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records. Note: This method is overwritten by the Validation module that’ll make sure that updates made with this method doesn’t get subjected to validation checks. Hence, attributes can be updated even if the full object isn’t valid.

Updates all the attributes from the passed-in Hash and saves the record. If the object is invalid, the saving will fail and false will be returned.

[Validate]