/vendor/rails/activerecord/lib/active_record/base.rb
Ruby | 3220 lines | 1575 code | 280 blank | 1365 comment | 163 complexity | 07303c415857b83811136e83861e582c MD5 | raw file
Possible License(s): ISC, LGPL-2.1
Large files files are truncated, but you can click here to view the full file
- require 'yaml'
- require 'set'
- require 'active_support/core_ext/class/attribute'
- module ActiveRecord #:nodoc:
- # Generic Active Record exception class.
- class ActiveRecordError < StandardError
- end
- # Raised when the single-table inheritance mechanism fails to locate the subclass
- # (for example due to improper usage of column that +inheritance_column+ points to).
- class SubclassNotFound < ActiveRecordError #:nodoc:
- end
- # Raised when an object assigned to an association has an incorrect type.
- #
- # class Ticket < ActiveRecord::Base
- # has_many :patches
- # end
- #
- # class Patch < ActiveRecord::Base
- # belongs_to :ticket
- # end
- #
- # # Comments are not patches, this assignment raises AssociationTypeMismatch.
- # @ticket.patches << Comment.new(:content => "Please attach tests to your patch.")
- class AssociationTypeMismatch < ActiveRecordError
- end
- # Raised when unserialized object's type mismatches one specified for serializable field.
- class SerializationTypeMismatch < ActiveRecordError
- end
- # Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt> misses adapter field).
- class AdapterNotSpecified < ActiveRecordError
- end
- # Raised when Active Record cannot find database adapter specified in <tt>config/database.yml</tt> or programmatically.
- class AdapterNotFound < ActiveRecordError
- end
- # Raised when connection to the database could not been established (for example when <tt>connection=</tt> is given a nil object).
- class ConnectionNotEstablished < ActiveRecordError
- end
- # Raised when Active Record cannot find record by given id or set of ids.
- class RecordNotFound < ActiveRecordError
- end
- # Raised by ActiveRecord::Base.save! and ActiveRecord::Base.create! methods when record cannot be
- # saved because record is invalid.
- class RecordNotSaved < ActiveRecordError
- end
- # Raised when SQL statement cannot be executed by the database (for example, it's often the case for MySQL when Ruby driver used is too old).
- class StatementInvalid < ActiveRecordError
- end
- # Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example, when using +find+ method)
- # does not match number of expected variables.
- #
- # For example, in
- #
- # Location.find :all, :conditions => ["lat = ? AND lng = ?", 53.7362]
- #
- # two placeholders are given but only one variable to fill them.
- class PreparedStatementInvalid < ActiveRecordError
- end
- # Raised on attempt to save stale record. Record is stale when it's being saved in another query after
- # instantiation, for example, when two users edit the same wiki page and one starts editing and saves
- # the page before the other.
- #
- # Read more about optimistic locking in ActiveRecord::Locking module RDoc.
- class StaleObjectError < ActiveRecordError
- end
- # Raised when association is being configured improperly or
- # user tries to use offset and limit together with has_many or has_and_belongs_to_many associations.
- class ConfigurationError < ActiveRecordError
- end
- # Raised on attempt to update record that is instantiated as read only.
- class ReadOnlyRecord < ActiveRecordError
- end
- # ActiveRecord::Transactions::ClassMethods.transaction uses this exception
- # to distinguish a deliberate rollback from other exceptional situations.
- # Normally, raising an exception will cause the +transaction+ method to rollback
- # the database transaction *and* pass on the exception. But if you raise an
- # ActiveRecord::Rollback exception, then the database transaction will be rolled back,
- # without passing on the exception.
- #
- # For example, you could do this in your controller to rollback a transaction:
- #
- # class BooksController < ActionController::Base
- # def create
- # Book.transaction do
- # book = Book.new(params[:book])
- # book.save!
- # if today_is_friday?
- # # The system must fail on Friday so that our support department
- # # won't be out of job. We silently rollback this transaction
- # # without telling the user.
- # raise ActiveRecord::Rollback, "Call tech support!"
- # end
- # end
- # # ActiveRecord::Rollback is the only exception that won't be passed on
- # # by ActiveRecord::Base.transaction, so this line will still be reached
- # # even on Friday.
- # redirect_to root_url
- # end
- # end
- class Rollback < ActiveRecordError
- end
- # Raised when attribute has a name reserved by Active Record (when attribute has name of one of Active Record instance methods).
- class DangerousAttributeError < ActiveRecordError
- end
- # Raised when you've tried to access a column which wasn't loaded by your finder.
- # Typically this is because <tt>:select</tt> has been specified.
- class MissingAttributeError < NoMethodError
- end
- # Raised when unknown attributes are supplied via mass assignment.
- class UnknownAttributeError < NoMethodError
- end
- # Raised when an error occurred while doing a mass assignment to an attribute through the
- # <tt>attributes=</tt> method. The exception has an +attribute+ property that is the name of the
- # offending attribute.
- class AttributeAssignmentError < ActiveRecordError
- attr_reader :exception, :attribute
- def initialize(message, exception, attribute)
- @exception = exception
- @attribute = attribute
- @message = message
- end
- end
- # Raised when there are multiple errors while doing a mass assignment through the +attributes+
- # method. The exception has an +errors+ property that contains an array of AttributeAssignmentError
- # objects, each corresponding to the error while assigning to an attribute.
- class MultiparameterAssignmentErrors < ActiveRecordError
- attr_reader :errors
- def initialize(errors)
- @errors = errors
- end
- end
- # Active Record objects don't specify their attributes directly, but rather infer them from the table definition with
- # which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change
- # is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain
- # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
- #
- # See the mapping rules in table_name and the full example in link:files/README.html for more insight.
- #
- # == Creation
- #
- # Active Records accept constructor parameters either in a hash or as a block. The hash method is especially useful when
- # you're receiving the data from somewhere else, like an HTTP request. It works like this:
- #
- # user = User.new(:name => "David", :occupation => "Code Artist")
- # user.name # => "David"
- #
- # You can also use block initialization:
- #
- # user = User.new do |u|
- # u.name = "David"
- # u.occupation = "Code Artist"
- # end
- #
- # And of course you can just create a bare object and specify the attributes after the fact:
- #
- # user = User.new
- # user.name = "David"
- # user.occupation = "Code Artist"
- #
- # == Conditions
- #
- # Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement.
- # The array form is to be used when the condition input is tainted and requires sanitization. The string form can
- # be used for statements that don't involve tainted data. The hash form works much like the array form, except
- # only equality and range is possible. Examples:
- #
- # class User < ActiveRecord::Base
- # def self.authenticate_unsafely(user_name, password)
- # find(:first, :conditions => "user_name = '#{user_name}' AND password = '#{password}'")
- # end
- #
- # def self.authenticate_safely(user_name, password)
- # find(:first, :conditions => [ "user_name = ? AND password = ?", user_name, password ])
- # end
- #
- # def self.authenticate_safely_simply(user_name, password)
- # find(:first, :conditions => { :user_name => user_name, :password => password })
- # end
- # end
- #
- # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection
- # attacks if the <tt>user_name</tt> and +password+ parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and
- # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+ before inserting them in the query,
- # which will ensure that an attacker can't escape the query and fake the login (or worse).
- #
- # When using multiple parameters in the conditions, it can easily become hard to read exactly what the fourth or fifth
- # question mark is supposed to represent. In those cases, you can resort to named bind variables instead. That's done by replacing
- # the question marks with symbols and supplying a hash with values for the matching symbol keys:
- #
- # Company.find(:first, :conditions => [
- # "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
- # { :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' }
- # ])
- #
- # Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
- # operator. For instance:
- #
- # Student.find(:all, :conditions => { :first_name => "Harvey", :status => 1 })
- # Student.find(:all, :conditions => params[:student])
- #
- # A range may be used in the hash to use the SQL BETWEEN operator:
- #
- # Student.find(:all, :conditions => { :grade => 9..12 })
- #
- # An array may be used in the hash to use the SQL IN operator:
- #
- # Student.find(:all, :conditions => { :grade => [9,11,12] })
- #
- # == Overwriting default accessors
- #
- # All column values are automatically available through basic accessors on the Active Record object, but sometimes you
- # want to specialize this behavior. This can be done by overwriting the default accessors (using the same
- # name as the attribute) and calling <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually change things.
- # Example:
- #
- # class Song < ActiveRecord::Base
- # # Uses an integer of seconds to hold the length of the song
- #
- # def length=(minutes)
- # write_attribute(:length, minutes.to_i * 60)
- # end
- #
- # def length
- # read_attribute(:length) / 60
- # end
- # end
- #
- # You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt> instead of <tt>write_attribute(:attribute, value)</tt> and
- # <tt>read_attribute(:attribute)</tt> as a shorter form.
- #
- # == Attribute query methods
- #
- # In addition to the basic accessors, query methods are also automatically available on the Active Record object.
- # Query methods allow you to test whether an attribute value is present.
- #
- # For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
- # to determine whether the user has a name:
- #
- # user = User.new(:name => "David")
- # user.name? # => true
- #
- # anonymous = User.new(:name => "")
- # anonymous.name? # => false
- #
- # == Accessing attributes before they have been typecasted
- #
- # Sometimes you want to be able to read the raw attribute data without having the column-determined typecast run its course first.
- # That can be done by using the <tt><attribute>_before_type_cast</tt> accessors that all attributes have. For example, if your Account model
- # has a <tt>balance</tt> attribute, you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>.
- #
- # This is especially useful in validation situations where the user might supply a string for an integer field and you want to display
- # the original string back in an error message. Accessing the attribute normally would typecast the string to 0, which isn't what you
- # want.
- #
- # == Dynamic attribute-based finders
- #
- # Dynamic attribute-based finders are a cleaner way of getting (and/or creating) objects by simple queries without turning to SQL. They work by
- # appending the name of an attribute to <tt>find_by_</tt>, <tt>find_last_by_</tt>, or <tt>find_all_by_</tt>, so you get finders like <tt>Person.find_by_user_name</tt>,
- # <tt>Person.find_all_by_last_name</tt>, and <tt>Payment.find_by_transaction_id</tt>. So instead of writing
- # <tt>Person.find(:first, :conditions => ["user_name = ?", user_name])</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
- # And instead of writing <tt>Person.find(:all, :conditions => ["last_name = ?", last_name])</tt>, you just do <tt>Person.find_all_by_last_name(last_name)</tt>.
- #
- # It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like
- # <tt>Person.find_by_user_name_and_password</tt> or even <tt>Payment.find_by_purchaser_and_state_and_country</tt>. So instead of writing
- # <tt>Person.find(:first, :conditions => ["user_name = ? AND password = ?", user_name, password])</tt>, you just do
- # <tt>Person.find_by_user_name_and_password(user_name, password)</tt>.
- #
- # It's even possible to use all the additional parameters to find. For example, the full interface for <tt>Payment.find_all_by_amount</tt>
- # is actually <tt>Payment.find_all_by_amount(amount, options)</tt>. And the full interface to <tt>Person.find_by_user_name</tt> is
- # actually <tt>Person.find_by_user_name(user_name, options)</tt>. So you could call <tt>Payment.find_all_by_amount(50, :order => "created_on")</tt>.
- # Also you may call <tt>Payment.find_last_by_amount(amount, options)</tt> returning the last record matching that amount and options.
- #
- # The same dynamic finder style can be used to create the object if it doesn't already exist. This dynamic finder is called with
- # <tt>find_or_create_by_</tt> and will return the object if it already exists and otherwise creates it, then returns it. Protected attributes won't be set unless they are given in a block. For example:
- #
- # # No 'Summer' tag exists
- # Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
- #
- # # Now the 'Summer' tag does exist
- # Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
- #
- # # Now 'Bob' exist and is an 'admin'
- # User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }
- #
- # Use the <tt>find_or_initialize_by_</tt> finder if you want to return a new record without saving it first. Protected attributes won't be set unless they are given in a block. For example:
- #
- # # No 'Winter' tag exists
- # winter = Tag.find_or_initialize_by_name("Winter")
- # winter.new_record? # true
- #
- # To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of
- # a list of parameters. For example:
- #
- # Tag.find_or_create_by_name(:name => "rails", :creator => current_user)
- #
- # That will either find an existing tag named "rails", or create a new one while setting the user that created it.
- #
- # == Saving arrays, hashes, and other non-mappable objects in text columns
- #
- # Active Record can serialize any object in text columns using YAML. To do so, you must specify this with a call to the class method +serialize+.
- # This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work. Example:
- #
- # class User < ActiveRecord::Base
- # serialize :preferences
- # end
- #
- # user = User.create(:preferences => { "background" => "black", "display" => large })
- # User.find(user.id).preferences # => { "background" => "black", "display" => large }
- #
- # You can also specify a class option as the second parameter that'll raise an exception if a serialized object is retrieved as a
- # descendant of a class not in the hierarchy. Example:
- #
- # class User < ActiveRecord::Base
- # serialize :preferences, Hash
- # end
- #
- # user = User.create(:preferences => %w( one two three ))
- # User.find(user.id).preferences # raises SerializationTypeMismatch
- #
- # == Single table inheritance
- #
- # Active Record allows inheritance by storing the name of the class in a column that by default is named "type" (can be changed
- # by overwriting <tt>Base.inheritance_column</tt>). This means that an inheritance looking like this:
- #
- # class Company < ActiveRecord::Base; end
- # class Firm < Company; end
- # class Client < Company; end
- # class PriorityClient < Client; end
- #
- # When you do <tt>Firm.create(:name => "37signals")</tt>, this record will be saved in the companies table with type = "Firm". You can then
- # fetch this row again using <tt>Company.find(:first, "name = '37signals'")</tt> and it will return a Firm object.
- #
- # If you don't have a type column defined in your table, single-table inheritance won't be triggered. In that case, it'll work just
- # like normal subclasses with no special magic for differentiating between them or reloading the right type with find.
- #
- # Note, all the attributes for all the cases are kept in the same table. Read more:
- # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
- #
- # == Connection to multiple databases in different models
- #
- # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection.
- # All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection.
- # For example, if Course is an ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
- # and Course and all of its subclasses will use this connection instead.
- #
- # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is
- # requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool.
- #
- # == Exceptions
- #
- # * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record.
- # * AdapterNotSpecified - The configuration hash used in <tt>establish_connection</tt> didn't include an
- # <tt>:adapter</tt> key.
- # * AdapterNotFound - The <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a non-existent adapter
- # (or a bad spelling of an existing one).
- # * AssociationTypeMismatch - The object assigned to the association wasn't of the type specified in the association definition.
- # * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
- # * ConnectionNotEstablished+ - No connection has been established. Use <tt>establish_connection</tt> before querying.
- # * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
- # or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
- # nothing was found, please check its documentation for further details.
- # * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
- # * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the
- # <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of AttributeAssignmentError
- # objects that should be inspected to determine which attributes triggered the errors.
- # * AttributeAssignmentError - An error occurred while doing a mass assignment through the <tt>attributes=</tt> method.
- # You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error.
- #
- # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
- # So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all
- # instances in the current object space.
- class Base
- ##
- # :singleton-method:
- # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed
- # on to any new database connections made and which can be retrieved on both a class and instance level by calling +logger+.
- cattr_accessor :logger, :instance_writer => false
- def self.inherited(child) #:nodoc:
- @@subclasses[self] ||= []
- @@subclasses[self] << child
- super
- end
- def self.reset_subclasses #:nodoc:
- nonreloadables = []
- subclasses.each do |klass|
- unless ActiveSupport::Dependencies.autoloaded? klass
- nonreloadables << klass
- next
- end
- klass.instance_variables.each { |var| klass.send(:remove_instance_variable, var) }
- klass.instance_methods(false).each { |m| klass.send :undef_method, m }
- end
- @@subclasses = {}
- nonreloadables.each { |klass| (@@subclasses[klass.superclass] ||= []) << klass }
- end
- @@subclasses = {}
- ##
- # :singleton-method:
- # Contains the database configuration - as is typically stored in config/database.yml -
- # as a Hash.
- #
- # For example, the following database.yml...
- #
- # development:
- # adapter: sqlite3
- # database: db/development.sqlite3
- #
- # production:
- # adapter: sqlite3
- # database: db/production.sqlite3
- #
- # ...would result in ActiveRecord::Base.configurations to look like this:
- #
- # {
- # 'development' => {
- # 'adapter' => 'sqlite3',
- # 'database' => 'db/development.sqlite3'
- # },
- # 'production' => {
- # 'adapter' => 'sqlite3',
- # 'database' => 'db/production.sqlite3'
- # }
- # }
- cattr_accessor :configurations, :instance_writer => false
- @@configurations = {}
- ##
- # :singleton-method:
- # Accessor for the prefix type that will be prepended to every primary key column name. The options are :table_name and
- # :table_name_with_underscore. If the first is specified, the Product class will look for "productid" instead of "id" as
- # the primary column. If the latter is specified, the Product class will look for "product_id" instead of "id". Remember
- # that this is a global setting for all Active Records.
- cattr_accessor :primary_key_prefix_type, :instance_writer => false
- @@primary_key_prefix_type = nil
- ##
- # :singleton-method:
- # Accessor for the name of the prefix string to prepend to every table name. So if set to "basecamp_", all
- # table names will be named like "basecamp_projects", "basecamp_people", etc. This is a convenient way of creating a namespace
- # for tables in a shared database. By default, the prefix is the empty string.
- #
- # If you are organising your models within modules you can add a prefix to the models within a namespace by defining
- # a singleton method in the parent module called table_name_prefix which returns your chosen prefix.
- cattr_accessor :table_name_prefix, :instance_writer => false
- @@table_name_prefix = ""
- ##
- # :singleton-method:
- # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
- # "people_basecamp"). By default, the suffix is the empty string.
- cattr_accessor :table_name_suffix, :instance_writer => false
- @@table_name_suffix = ""
- ##
- # :singleton-method:
- # Indicates whether table names should be the pluralized versions of the corresponding class names.
- # If true, the default table name for a Product class will be +products+. If false, it would just be +product+.
- # See table_name for the full rules on table/class naming. This is true, by default.
- cattr_accessor :pluralize_table_names, :instance_writer => false
- @@pluralize_table_names = true
- ##
- # :singleton-method:
- # Determines whether to use ANSI codes to colorize the logging statements committed by the connection adapter. These colors
- # make it much easier to overview things during debugging (when used through a reader like +tail+ and on a black background), but
- # may complicate matters if you use software like syslog. This is true, by default.
- cattr_accessor :colorize_logging, :instance_writer => false
- @@colorize_logging = true
- ##
- # :singleton-method:
- # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates and times from the database.
- # This is set to :local by default.
- cattr_accessor :default_timezone, :instance_writer => false
- @@default_timezone = :local
- ##
- # :singleton-method:
- # Specifies the format to use when dumping the database schema with Rails'
- # Rakefile. If :sql, the schema is dumped as (potentially database-
- # specific) SQL statements. If :ruby, the schema is dumped as an
- # ActiveRecord::Schema file which can be loaded into any database that
- # supports migrations. Use :ruby if you want to have different database
- # adapters for, e.g., your development and test environments.
- cattr_accessor :schema_format , :instance_writer => false
- @@schema_format = :ruby
- ##
- # :singleton-method:
- # Specify whether or not to use timestamps for migration numbers
- cattr_accessor :timestamped_migrations , :instance_writer => false
- @@timestamped_migrations = true
- # Determine whether to store the full constant name including namespace when using STI
- class_attribute :store_full_sti_class
- self.store_full_sti_class = false
- # Stores the default scope for the class
- class_inheritable_accessor :default_scoping, :instance_writer => false
- self.default_scoping = []
- class << self # Class methods
- # Find operates with four 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 be matched, +nil+ is returned. Use
- # <tt>Model.find(:first, *args)</tt> or its shortcut <tt>Model.first(*args)</tt>.
- # * Find last - This will return the last record matched by the options used. These options can either be specific
- # conditions or merely an order. If no record can be matched, +nil+ is returned. Use
- # <tt>Model.find(:last, *args)</tt> or its shortcut <tt>Model.last(*args)</tt>.
- # * Find all - This will return all the records matched by the options used.
- # If no records are found, an empty array is returned. Use
- # <tt>Model.find(:all, *args)</tt> or its shortcut <tt>Model.all(*args)</tt>.
- #
- # All approaches accept an options hash as their last parameter.
- #
- # ==== Parameters
- #
- # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1", <tt>[ "user_name = ?", username ]</tt>, or <tt>["user_name = :user_name", { :user_name => user_name }]</tt>. See conditions in the intro.
- # * <tt>:order</tt> - An SQL fragment like "created_at DESC, name".
- # * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
- # * <tt>:having</tt> - Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
- # * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned.
- # * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5, it would skip rows 0 through 4.
- # * <tt>:joins</tt> - Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed),
- # named associations in the same form used for the <tt>:include</tt> option, which will perform an <tt>INNER JOIN</tt> on the associated table(s),
- # or an array containing a mixture of both strings and named associations.
- # If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns.
- # Pass <tt>:readonly => false</tt> to override.
- # * <tt>:include</tt> - Names associations that should be loaded alongside. The symbols named refer
- # to already defined associations. See eager loading under Associations.
- # * <tt>:select</tt> - 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. Takes a string with the SELECT SQL fragment (e.g. "id, name").
- # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an alternate table name (or even the name
- # of a database view).
- # * <tt>:readonly</tt> - Mark the returned records read-only so they cannot be saved or updated.
- # * <tt>:lock</tt> - An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE".
- # <tt>:lock => true</tt> gives connection's default exclusive lock, usually "FOR UPDATE".
- #
- # ==== Examples
- #
- # # 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 the object with ID = 1
- # Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
- #
- # Note that returned records may not be in the same order as the ids you
- # provide since database rows are unordered. Give an explicit <tt>:order</tt>
- # to ensure the results are sorted.
- #
- # ==== Examples
- #
- # # 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, :conditions => [ "user_name = :u", { :u => user_name }])
- # Person.find(:first, :order => "created_on DESC", :offset => 5)
- #
- # # find last
- # Person.find(:last) # returns the last object fetched by SELECT * FROM people
- # Person.find(:last, :conditions => [ "user_name = ?", user_name])
- # Person.find(:last, :order => "created_on DESC", :offset => 5)
- #
- # # 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, :conditions => { :friends => ["Bob", "Steve", "Fred"] }
- # Person.find(:all, :offset => 10, :limit => 10)
- # Person.find(:all, :include => [ :account, :friends ])
- # Person.find(:all, :group => "category")
- #
- # Example for find with a lock: Imagine two concurrent transactions:
- # each will read <tt>person.visits == 2</tt>, add 1 to it, and save, resulting
- # in two saves of <tt>person.visits = 3</tt>. By locking the row, the second
- # transaction has to wait until the first is finished; we get the
- # expected <tt>person.visits == 4</tt>.
- #
- # Person.transaction do
- # person = Person.find(1, :lock => true)
- # person.visits += 1
- # person.save!
- # end
- def find(*args)
- options = args.extract_options!
- validate_find_options(options)
- set_readonly_option!(options)
- case args.first
- when :first then find_initial(options)
- when :last then find_last(options)
- when :all then find_every(options)
- else find_from_ids(args, options)
- end
- end
- # A convenience wrapper for <tt>find(:first, *args)</tt>. You can pass in all the
- # same arguments to this method as you can to <tt>find(:first)</tt>.
- def first(*args)
- find(:first, *args)
- end
- # A convenience wrapper for <tt>find(:last, *args)</tt>. You can pass in all the
- # same arguments to this method as you can to <tt>find(:last)</tt>.
- def last(*args)
- find(:last, *args)
- end
- # This is an alias for find(:all). You can pass in all the same arguments to this method as you can
- # to find(:all)
- def all(*args)
- find(:all, *args)
- end
- # Executes a custom SQL query against your database and returns all the results. The results will
- # be returned as an array with columns requested encapsulated as attributes of the model you call
- # this method from. If you call <tt>Product.find_by_sql</tt> then the results will be returned in
- # a Product object with the attributes you specified in the SQL query.
- #
- # If you call a complicated SQL query which spans multiple tables the columns specified by the
- # SELECT will be attributes of the model, whether or not they are columns of the corresponding
- # table.
- #
- # The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be
- # no database agnostic conversions performed. This should be a last resort because using, for example,
- # MySQL specific terms will lock you to using that particular database engine or require you to
- # change your call if you switch engines.
- #
- # ==== Examples
- # # A simple SQL query spanning multiple tables
- # Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
- # > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
- #
- # # You can use the same string replacement techniques as you can with ActiveRecord#find
- # Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
- # > [#<Post:0x36bff9c @attributes={"first_name"=>"The Cheap Man Buys Twice"}>, ...]
- def find_by_sql(sql)
- connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) }
- end
- # Returns true if a record exists in the table that matches the +id+ or
- # conditions given, or false otherwise. The argument can take five forms:
- #
- # * Integer - Finds the record with this primary key.
- # * String - Finds the record with a primary key corresponding to this
- # string (such as <tt>'5'</tt>).
- # * Array - Finds the record that matches these +find+-style conditions
- # (such as <tt>['color = ?', 'red']</tt>).
- # * Hash - Finds the record that matches these +find+-style conditions
- # (such as <tt>{:color => 'red'}</tt>).
- # * No args - Returns false if the table is empty, true otherwise.
- #
- # For more information about specifying conditions as a Hash or Array,
- # see the Conditions section in the introduction to ActiveRecord::Base.
- #
- # Note: You can't pass in a condition as a string (like <tt>name =
- # 'Jamie'</tt>), since it would be sanitized and then queried against
- # the primary key column, like <tt>id = 'name = \'Jamie\''</tt>.
- #
- # ==== Examples
- # Person.exists?(5)
- # Person.exists?('5')
- # Person.exists?(:name => "David")
- # Person.exists?(['name LIKE ?', "%#{query}%"])
- # Person.exists?
- def exists?(id_or_conditions = {})
- find_initial(
- :select => "#{quoted_table_name}.#{primary_key}",
- :conditions => expand_id_conditions(id_or_conditions)) ? true : false
- end
- # Creates an object (or multiple objects) and saves it to the database, if validations pass.
- # The resulting object is returned whether the object was saved successfully to the database or not.
- #
- # The +attributes+ parameter can be either be a Hash or an Array of Hashes. These Hashes describe the
- # attributes on the objects that are to be created.
- #
- # ==== Examples
- # # Create a single new object
- # User.create(:first_name => 'Jamie')
- #
- # # Create an Array of new objects
- # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])
- #
- # # Create a single object and pass it into a block to set other attributes.
- # User.create(:first_name => 'Jamie') do |u|
- # u.is_admin = false
- # end
- #
- # # Creating an Array of new objects using a block, where the block is executed for each object:
- # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u|
- # u.is_admin = false
- # end
- def create(attributes = nil, &block)
- if attributes.is_a?(Array)
- attributes.collect { |attr| create(attr, &block) }
- else
- object = new(attributes)
- yield(object) if block_given?
- object.save
- object
- end
- end
- # Updates an object (or multiple objects) and saves it to the database, if validations pass.
- # The resulting object is returned whether the object was saved successfully to the database or not.
- #
- # ==== Parameters
- #
- # * +id+ - This should be the id or an array of ids to be updated.
- # * +attributes+ - This should be a hash of attributes to be set on the object, or an array of hashes.
- #
- # ==== Examples
- #
- # # Updating one record:
- # Person.update(15, :user_name => 'Samuel', :group => 'expert')
- #
- # # Updating multiple records:
- # people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
- # Person.update(people.keys, people.values)
- def update(id, attributes)
- if id.is_a?(Array)
- idx = -1
- id.collect { |one_id| idx += 1; update(one_id, attributes[idx]) }
- else
- object = find(id)
- object.update_attributes(attributes)
- object
- end
- end
- # Deletes the row with a primary key matching the +id+ argument, using a
- # SQL +DELETE+ statement, and returns the number of rows deleted. Active
- # Record objects are not instantiated, so the object's callbacks are not
- # executed, including any <tt>:dependent</tt> association options or
- # Observer methods.
- #
- # You can delete multiple rows at once by passing an Array of <tt>id</tt>s.
- #
- # Note: Although it is often much faster than the alternative,
- # <tt>#destroy</tt>, skipping callbacks might bypass business logic in
- # your application that ensures referential integrity or performs other
- # essential jobs.
- #
- # ==== Examples
- #
- # # Delete a single row
- # Todo.delete(1)
- #
- # # Delete multiple rows
- # Todo.delete([2,3,4])
- def delete(id)
- delete_all([ "#{connection.quote_column_name(primary_key)} IN (?)", id ])
- end
- # Destroy an object (or multiple objects) that has the given id, the object is instantiated first,
- # therefore all callbacks and filters are fired off before the object is deleted. This method is
- # less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.
- #
- # This essentially finds the object (or multiple objects) with the given id, creates a new object
- # from the attributes, and then calls destroy on it.
- #
- # ==== Parameters
- #
- # * +id+ - Can be either an Integer or an Array of Integers.
- #
- # ==== Examples
- #
- # # Destroy a single object
- # Todo.destroy(1)
- #
- # # Destroy multiple objects
- # todos = [1,2,3]
- # Todo.destroy(todos)
- def destroy(id)
- if id.is_a?(Array)
- id.map { |one_id| destroy(one_id) }
- else
- find(id).destroy
- end
- end
- # Updates all records with details given if they match a set of conditions supplied, limits and order can
- # also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the
- # database. It does not instantiate the involved models and it does not trigger Active Record callbacks.
- #
- # ==== Parameters
- #
- # * +updates+ - A string of column and value pairs that will be set on any records that match conditions. This creates the SET clause of the generated SQL.
- # * +conditions+ - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro for more info.
- # * +options+ - Additional options are <tt>:limit</tt> and <tt>:order</tt>, see the examples for usage.
- #
- # ==== Examples
- #
- # # Update all billing objects with the 3 different attributes given
- # Billing.update_all( "category = 'authorized', approved = 1, author = 'David'" )
- #
- # # Update records that match our conditions
- # Billing.update_all( "author = 'David'", "title LIKE '%Rails%'" )
- #
- # # Update records that match our conditions but limit it to 5 ordered by date
- # Billing.update_all( "author = 'David'", "title LIKE '%Rails%'",
- # :order => 'created_at', :limit => 5 )
- def update_all(updates, conditions = nil, options = {})
- sql = "UPDATE #{quoted_table_name} SET #{sanitize_sql_for_assignment(updates)} "
- scope = scope(:find)
- select_sql = ""
- add_conditions!(select_sql, conditions, scope)
- if options.has_key?(:limit) || (scope && scope[:limit])
- # Only take order from scope if limit is also provided by scope, this
- # is useful for updating a has_many association with a limit.
- add_order!(select_sql, options[:order], scope)
- add_limit!(select_sql, options, scope)
- sql.concat(connection.limited_update_conditions(select_sql, quoted_table_name, connection.quote_column_name(primary_key)))
- else
- add_order!(select_sql, options[:order], nil)
- sql.concat(select_sql)
- end
- connection.update(sql, "#{name} Update")
- end
- # Destroys the records matching +conditions+ by instantiating each
- # record and calling its +destroy+ method. Each object's callbacks are
- # executed (including <tt>:dependent</tt> association options and
- # +before_destroy+/+after_destroy+ Observer methods). Returns the
- # collection of objects that were destroyed; each will be frozen, to
- # reflect that no changes should be made (since they can't be
- # persisted).
- #
- # Note: Instantiation, callback execution, and deletion of each
- # record can be time consuming when you're removing many records at
- # once. It generates at least one SQL +DELETE+ query per record (or
- # possibly more, to enforce your callbacks). If you want to delete many
- # rows quickly, without concern for their associations or callbacks, use
- # +delete_all+ instead.
- #
- # ==== Parameters
- #
- # * +conditions+ - A string, array, or hash that specifies which records
- # to destroy. If omitted, all records are destroyed. See the
- # Conditions section in the introduction to ActiveRecord::Base for
- # more information.
- #
- # ==== Examples
- #
- # Person.destroy_all("last_login < '2004-04-04'")
- # Person.destroy_all(:status => "inactive")
- def destroy_all(conditions = nil)
- find(:all, :conditions => conditions).each { |object| object.destroy }
- end
- # Deletes the records matching +conditions+ without instantiating the records first, and hence not
- # calling the +destroy+ method nor invoking callbacks. This is a single SQL DELETE statement that
- # goes straight to the database, much more efficient than +destroy_all+. Be careful with relations
- # though, in particular <tt>:dependent</tt> rules defined on associations are not honored. Returns
- # the number of rows affected.
- #
- # ==== Parameters
- #
- # * +conditions+ - Conditions are specified the same way as with +find+ method.
- #
- # ==== Example
- #
- # Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
- # Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
- #
- # Both calls delete the affected posts all at once with a single DELETE statement. If you need to destroy dependent
- # associations or call your <tt>before_*</tt> or +after_destroy+ callbacks, use the +destroy_all+ method instead.
- def delete_all(conditions = nil)
- sql = "DELETE FROM #{quoted_table_name} "
- add_conditions!(sql, conditions, scope(:find))
- connection.delete(sql, "#{name} Delete all")
- end
- # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
- # The use of this method should be restricted to complicated SQL queries that can't be executed
- # using the ActiveRecord::Calculations class methods. Look into those before using this.
- #
- # ==== Parameters
- #
- # * +sql+ - An SQL statement which should return a count query from the database, see the example below.
- #
- # ==== Examples
- #
- # Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
- def count_by_sql(sql)
- sql = sanitize_conditions(sql)
- connection.select_value(sql, "#{name} Count").to_i
- end
- # Resets one or more counter caches to their correct value using an SQL
- # count query. This is useful when adding new counter caches, or if the
- # counter has been corrupted or modified directly by SQL.
- #
- # ==== Parameters
- #
- # * +id+ - The id of the object you wish to reset a counter on.
- # * +counters+ - One or more counter names to reset
- #
- # ==== Examples
- #
- # # For Post with id #1 records reset the comments_count
- # Post.reset_counters(1, :comments)
- def reset_counters(id, *counters)
- object = find(id)
- counters.each do |association|
- child_class = reflect_on_association(association.to_sym).klass
- belongs_name = self.name.demodulize.underscore.to_sym
- counter_name = child_class.reflect_on_association(belongs_name).counter_cache_column
- value = object.send(association).count
- connection.update(<<-CMD, "#{name} UPDATE")
- UPDATE #{quoted_table_name}
- SET #{connection.quote_column_name(counter_name)} = #{value}
- WHERE #{connection.quote_column_name(primary_key)} = #{quote_value(object.id)}
- CMD
- end
- return true
- end
- # A generic "counter updater" implementation, intended primarily to be
- # used by increment_counter and decrement_counter, but which may also
- # be useful on its own. It simply does a direct SQL update for the record
- # with the given ID, altering the given hash of counters by the amount
- # given by the corresponding value:
- #
- # ==== Parameters
- #
- # * +id+ - The id of the object you wish to update a counter on or an Array of ids.
- # * +counters+ - An Array of Hashes containing the names of the fields
- # to update as keys and the amount to update the field by as values.
- #
- # ==== Examples
- #
- # # For the Post with id of 5, decrement the comment_count by 1, and
- # # increment the action_count by 1
- # Post.update_counters 5, :comment_count => -1, :action_count => 1
- # # Executes the following SQL:
- # # UPDATE posts
- # # SET comment_count = comment_count - 1,
- # # action_count = action_count + 1
- # # WHERE id = 5
- #
- # # For the Posts with id of 10 and 15, increment the comment_count by 1
- # Post.update_counters [10, 15], :comment_count => 1
- # # Executes the following SQL:
- # # UPDATE posts
- # # SET comment_count = comment_count + 1,
- # # WHERE id IN (10, 15)
- def update_counters(id, counters)
- updates = counters.map do |counter_name, value|
- operator = value < 0 ? '-' : '+'
- quoted_column = connection.quote_column_name(counter_name)
- "#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{value.abs}"
- end
- update_all(updates.join(', '), primary_key => id )
- end
- # Increment a number field by one, usually representing a count.
- #
- # This is used for caching aggregate values, so that they don't need to be computed every time.
- # For example, a DiscussionBoard may cache post_count and comment_count otherwise every time the board is
- # shown it would have to run an SQL query to find how many posts and comments there are.
- #
- # ==== Parameters
- #
- # * +counter_name+ - The name of the field that should be incremented.
- # * +id+ - The id of the object that should be incremented.
- #
- # ==== Examples
- #
- # # Increment the post_count column for the record with an id of 5
- # DiscussionBoard.increment_counter(:post_c…
Large files files are truncated, but you can click here to view the full file