5 module ActiveRecord #:nodoc:
6 class ActiveRecordError < StandardError #:nodoc:
8 class SubclassNotFound < ActiveRecordError #:nodoc:
10 class AssociationTypeMismatch < ActiveRecordError #:nodoc:
12 class SerializationTypeMismatch < ActiveRecordError #:nodoc:
14 class AdapterNotSpecified < ActiveRecordError # :nodoc:
16 class AdapterNotFound < ActiveRecordError # :nodoc:
18 class ConnectionNotEstablished < ActiveRecordError #:nodoc:
20 class ConnectionFailed < ActiveRecordError #:nodoc:
22 class RecordNotFound < ActiveRecordError #:nodoc:
24 class RecordNotSaved < ActiveRecordError #:nodoc:
26 class StatementInvalid < ActiveRecordError #:nodoc:
28 class PreparedStatementInvalid < ActiveRecordError #:nodoc:
30 class StaleObjectError < ActiveRecordError #:nodoc:
32 class ConfigurationError < ActiveRecordError #:nodoc:
34 class ReadOnlyRecord < ActiveRecordError #:nodoc:
36 class Rollback < ActiveRecordError #:nodoc:
38 class DangerousAttributeError < ActiveRecordError #:nodoc:
41 # Raised when you've tried to access a column which wasn't
42 # loaded by your finder. Typically this is because :select
44 class MissingAttributeError < NoMethodError
47 class AttributeAssignmentError < ActiveRecordError #:nodoc:
48 attr_reader :exception, :attribute
49 def initialize(message, exception, attribute)
50 @exception = exception
51 @attribute = attribute
56 class MultiparameterAssignmentErrors < ActiveRecordError #:nodoc:
58 def initialize(errors)
63 # Active Record objects don't specify their attributes directly, but rather infer them from the table definition with
64 # which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change
65 # is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain
66 # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
68 # See the mapping rules in table_name and the full example in link:files/README.html for more insight.
72 # Active Records accept constructor parameters either in a hash or as a block. The hash method is especially useful when
73 # you're receiving the data from somewhere else, like an HTTP request. It works like this:
75 # user = User.new(:name => "David", :occupation => "Code Artist")
76 # user.name # => "David"
78 # You can also use block initialization:
80 # user = User.new do |u|
82 # u.occupation = "Code Artist"
85 # And of course you can just create a bare object and specify the attributes after the fact:
89 # user.occupation = "Code Artist"
93 # Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement.
94 # The array form is to be used when the condition input is tainted and requires sanitization. The string form can
95 # be used for statements that don't involve tainted data. The hash form works much like the array form, except
96 # only equality and range is possible. Examples:
98 # class User < ActiveRecord::Base
99 # def self.authenticate_unsafely(user_name, password)
100 # find(:first, :conditions => "user_name = '#{user_name}' AND password = '#{password}'")
103 # def self.authenticate_safely(user_name, password)
104 # find(:first, :conditions => [ "user_name = ? AND password = ?", user_name, password ])
107 # def self.authenticate_safely_simply(user_name, password)
108 # find(:first, :conditions => { :user_name => user_name, :password => password })
112 # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection
113 # attacks if the <tt>user_name</tt> and +password+ parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and
114 # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+ before inserting them in the query,
115 # which will ensure that an attacker can't escape the query and fake the login (or worse).
117 # When using multiple parameters in the conditions, it can easily become hard to read exactly what the fourth or fifth
118 # question mark is supposed to represent. In those cases, you can resort to named bind variables instead. That's done by replacing
119 # the question marks with symbols and supplying a hash with values for the matching symbol keys:
121 # Company.find(:first, [
122 # "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
123 # { :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' }
126 # Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
127 # operator. For instance:
129 # Student.find(:all, :conditions => { :first_name => "Harvey", :status => 1 })
130 # Student.find(:all, :conditions => params[:student])
132 # A range may be used in the hash to use the SQL BETWEEN operator:
134 # Student.find(:all, :conditions => { :grade => 9..12 })
136 # == Overwriting default accessors
138 # All column values are automatically available through basic accessors on the Active Record object, but sometimes you
139 # want to specialize this behavior. This can be done by overwriting the default accessors (using the same
140 # name as the attribute) and calling read_attribute(attr_name) and write_attribute(attr_name, value) to actually change things.
143 # class Song < ActiveRecord::Base
144 # # Uses an integer of seconds to hold the length of the song
146 # def length=(minutes)
147 # write_attribute(:length, minutes * 60)
151 # read_attribute(:length) / 60
155 # You can alternatively use self[:attribute]=(value) and self[:attribute] instead of write_attribute(:attribute, value) and
156 # read_attribute(:attribute) as a shorter form.
158 # == Accessing attributes before they have been typecasted
160 # Sometimes you want to be able to read the raw attribute data without having the column-determined typecast run its course first.
161 # That can be done by using the <attribute>_before_type_cast accessors that all attributes have. For example, if your Account model
162 # has a balance attribute, you can call account.balance_before_type_cast or account.id_before_type_cast.
164 # This is especially useful in validation situations where the user might supply a string for an integer field and you want to display
165 # the original string back in an error message. Accessing the attribute normally would typecast the string to 0, which isn't what you
168 # == Dynamic attribute-based finders
170 # Dynamic attribute-based finders are a cleaner way of getting (and/or creating) objects by simple queries without turning to SQL. They work by
171 # appending the name of an attribute to <tt>find_by_</tt> or <tt>find_all_by_</tt>, so you get finders like Person.find_by_user_name,
172 # Person.find_all_by_last_name, Payment.find_by_transaction_id. So instead of writing
173 # <tt>Person.find(:first, ["user_name = ?", user_name])</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
174 # And instead of writing <tt>Person.find(:all, ["last_name = ?", last_name])</tt>, you just do <tt>Person.find_all_by_last_name(last_name)</tt>.
176 # It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like
177 # <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
178 # <tt>Person.find(:first, ["user_name = ? AND password = ?", user_name, password])</tt>, you just do
179 # <tt>Person.find_by_user_name_and_password(user_name, password)</tt>.
181 # It's even possible to use all the additional parameters to find. For example, the full interface for Payment.find_all_by_amount
182 # is actually Payment.find_all_by_amount(amount, options). And the full interface to Person.find_by_user_name is
183 # actually Person.find_by_user_name(user_name, options). So you could call <tt>Payment.find_all_by_amount(50, :order => "created_on")</tt>.
185 # The same dynamic finder style can be used to create the object if it doesn't already exist. This dynamic finder is called with
186 # <tt>find_or_create_by_</tt> and will return the object if it already exists and otherwise creates it, then returns it. Example:
188 # # No 'Summer' tag exists
189 # Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
191 # # Now the 'Summer' tag does exist
192 # Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
194 # Use the <tt>find_or_initialize_by_</tt> finder if you want to return a new record without saving it first. Example:
196 # # No 'Winter' tag exists
197 # winter = Tag.find_or_initialize_by_name("Winter")
198 # winter.new_record? # true
200 # To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of
201 # a list of parameters. For example:
203 # Tag.find_or_create_by_name(:name => "rails", :creator => current_user)
205 # That will either find an existing tag named "rails", or create a new one while setting the user that created it.
207 # == Saving arrays, hashes, and other non-mappable objects in text columns
209 # 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+.
210 # This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work. Example:
212 # class User < ActiveRecord::Base
213 # serialize :preferences
216 # user = User.create(:preferences => { "background" => "black", "display" => large })
217 # User.find(user.id).preferences # => { "background" => "black", "display" => large }
219 # You can also specify a class option as the second parameter that'll raise an exception if a serialized object is retrieved as a
220 # descendent of a class not in the hierarchy. Example:
222 # class User < ActiveRecord::Base
223 # serialize :preferences, Hash
226 # user = User.create(:preferences => %w( one two three ))
227 # User.find(user.id).preferences # raises SerializationTypeMismatch
229 # == Single table inheritance
231 # Active Record allows inheritance by storing the name of the class in a column that by default is named "type" (can be changed
232 # by overwriting <tt>Base.inheritance_column</tt>). This means that an inheritance looking like this:
234 # class Company < ActiveRecord::Base; end
235 # class Firm < Company; end
236 # class Client < Company; end
237 # class PriorityClient < Client; end
239 # When you do Firm.create(:name => "37signals"), this record will be saved in the companies table with type = "Firm". You can then
240 # fetch this row again using Company.find(:first, "name = '37signals'") and it will return a Firm object.
242 # 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
243 # like normal subclasses with no special magic for differentiating between them or reloading the right type with find.
245 # Note, all the attributes for all the cases are kept in the same table. Read more:
246 # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
248 # == Connection to multiple databases in different models
250 # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection.
251 # All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection.
252 # For example, if Course is an ActiveRecord::Base, but resides in a different database, you can just say Course.establish_connection
253 # and Course *and all its subclasses* will use this connection instead.
255 # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is
256 # requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool.
260 # * +ActiveRecordError+ -- generic error class and superclass of all other errors raised by Active Record
261 # * +AdapterNotSpecified+ -- the configuration hash used in <tt>establish_connection</tt> didn't include an
262 # <tt>:adapter</tt> key.
263 # * +AdapterNotFound+ -- the <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a non-existent adapter
264 # (or a bad spelling of an existing one).
265 # * +AssociationTypeMismatch+ -- the object assigned to the association wasn't of the type specified in the association definition.
266 # * +SerializationTypeMismatch+ -- the serialized object wasn't of the class specified as the second parameter.
267 # * +ConnectionNotEstablished+ -- no connection has been established. Use <tt>establish_connection</tt> before querying.
268 # * +RecordNotFound+ -- no record responded to the find* method.
269 # Either the row with the given ID doesn't exist or the row didn't meet the additional restrictions.
270 # * +StatementInvalid+ -- the database server rejected the SQL statement. The precise error is added in the message.
271 # Either the record with the given ID doesn't exist or the record didn't meet the additional restrictions.
272 # * +MultiparameterAssignmentErrors+ -- collection of errors that occurred during a mass assignment using the
273 # +attributes=+ method. The +errors+ property of this exception contains an array of +AttributeAssignmentError+
274 # objects that should be inspected to determine which attributes triggered the errors.
275 # * +AttributeAssignmentError+ -- an error occurred while doing a mass assignment through the +attributes=+ method.
276 # You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error.
278 # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
279 # So it's possible to assign a logger to the class through Base.logger= which will then be used by all
280 # instances in the current object space.
282 # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed
283 # on to any new database connections made and which can be retrieved on both a class and instance level by calling +logger+.
284 cattr_accessor :logger, :instance_writer => false
286 def self.inherited(child) #:nodoc:
287 @@subclasses[self] ||= []
288 @@subclasses[self] << child
292 def self.reset_subclasses #:nodoc:
294 subclasses.each do |klass|
295 unless Dependencies.autoloaded? klass
296 nonreloadables << klass
299 klass.instance_variables.each { |var| klass.send(:remove_instance_variable, var) }
300 klass.instance_methods(false).each { |m| klass.send :undef_method, m }
303 nonreloadables.each { |klass| (@@subclasses[klass.superclass] ||= []) << klass }
308 cattr_accessor :configurations, :instance_writer => false
309 @@configurations = {}
311 # Accessor for the prefix type that will be prepended to every primary key column name. The options are :table_name and
312 # :table_name_with_underscore. If the first is specified, the Product class will look for "productid" instead of "id" as
313 # the primary column. If the latter is specified, the Product class will look for "product_id" instead of "id". Remember
314 # that this is a global setting for all Active Records.
315 cattr_accessor :primary_key_prefix_type, :instance_writer => false
316 @@primary_key_prefix_type = nil
318 # Accessor for the name of the prefix string to prepend to every table name. So if set to "basecamp_", all
319 # table names will be named like "basecamp_projects", "basecamp_people", etc. This is a convenient way of creating a namespace
320 # for tables in a shared database. By default, the prefix is the empty string.
321 cattr_accessor :table_name_prefix, :instance_writer => false
322 @@table_name_prefix = ""
324 # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
325 # "people_basecamp"). By default, the suffix is the empty string.
326 cattr_accessor :table_name_suffix, :instance_writer => false
327 @@table_name_suffix = ""
329 # Indicates whether table names should be the pluralized versions of the corresponding class names.
330 # If true, the default table name for a +Product+ class will be +products+. If false, it would just be +product+.
331 # See table_name for the full rules on table/class naming. This is true, by default.
332 cattr_accessor :pluralize_table_names, :instance_writer => false
333 @@pluralize_table_names = true
335 # Determines whether to use ANSI codes to colorize the logging statements committed by the connection adapter. These colors
336 # make it much easier to overview things during debugging (when used through a reader like +tail+ and on a black background), but
337 # may complicate matters if you use software like syslog. This is true, by default.
338 cattr_accessor :colorize_logging, :instance_writer => false
339 @@colorize_logging = true
341 # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates and times from the database.
342 # This is set to :local by default.
343 cattr_accessor :default_timezone, :instance_writer => false
344 @@default_timezone = :local
346 # Determines whether to use a connection for each thread, or a single shared connection for all threads.
347 # Defaults to false. Set to true if you're writing a threaded application.
348 cattr_accessor :allow_concurrency, :instance_writer => false
349 @@allow_concurrency = false
351 # Specifies the format to use when dumping the database schema with Rails'
352 # Rakefile. If :sql, the schema is dumped as (potentially database-
353 # specific) SQL statements. If :ruby, the schema is dumped as an
354 # ActiveRecord::Schema file which can be loaded into any database that
355 # supports migrations. Use :ruby if you want to have different database
356 # adapters for, e.g., your development and test environments.
357 cattr_accessor :schema_format , :instance_writer => false
358 @@schema_format = :ruby
360 class << self # Class methods
361 # Find operates with three different retrieval approaches:
363 # * 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]).
364 # If no record can be found for all of the listed ids, then RecordNotFound will be raised.
365 # * Find first: This will return the first record matched by the options used. These options can either be specific
366 # conditions or merely an order. If no record can be matched, nil is returned.
367 # * Find all: This will return all the records matched by the options used. If no records are found, an empty array is returned.
369 # All approaches accept an options hash as their last parameter. The options are:
371 # * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro.
372 # * <tt>:order</tt>: An SQL fragment like "created_at DESC, name".
373 # * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
374 # * <tt>:limit</tt>: An integer determining the limit on the number of rows that should be returned.
375 # * <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.
376 # * <tt>:joins</tt>: An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (Rarely needed).
377 # Accepts named associations in the form of :include, which will perform an INNER JOIN on the associated table(s).
378 # The records will be returned read-only since they will have attributes that do not correspond to the table's columns.
379 # Pass :readonly => false to override.
380 # See adding joins for associations under Associations.
381 # * <tt>:include</tt>: Names associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer
382 # to already defined associations. See eager loading under Associations.
383 # * <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
384 # include the joined columns.
385 # * <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
386 # of a database view).
387 # * <tt>:readonly</tt>: Mark the returned records read-only so they cannot be saved or updated.
388 # * <tt>:lock</tt>: An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE".
389 # :lock => true gives connection's default exclusive lock, usually "FOR UPDATE".
391 # Examples for find by id:
392 # Person.find(1) # returns the object for ID = 1
393 # Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
394 # Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
395 # Person.find([1]) # returns an array for the object with ID = 1
396 # Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
398 # Note that returned records may not be in the same order as the ids you
399 # provide since database rows are unordered. Give an explicit :order
400 # to ensure the results are sorted.
402 # Examples for find first:
403 # Person.find(:first) # returns the first object fetched by SELECT * FROM people
404 # Person.find(:first, :conditions => [ "user_name = ?", user_name])
405 # Person.find(:first, :order => "created_on DESC", :offset => 5)
407 # Examples for find all:
408 # Person.find(:all) # returns an array of objects for all the rows fetched by SELECT * FROM people
409 # Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50)
410 # Person.find(:all, :offset => 10, :limit => 10)
411 # Person.find(:all, :include => [ :account, :friends ])
412 # Person.find(:all, :group => "category")
414 # Example for find with a lock. Imagine two concurrent transactions:
415 # each will read person.visits == 2, add 1 to it, and save, resulting
416 # in two saves of person.visits = 3. By locking the row, the second
417 # transaction has to wait until the first is finished; we get the
418 # expected person.visits == 4.
419 # Person.transaction do
420 # person = Person.find(1, :lock => true)
425 options = args.extract_options!
426 # Note: we extract any :joins option with a non-string value from the options, and turn it into
427 # an internal option :ar_joins. This allows code called from here to find the ar_joins, and
428 # it bypasses marking the result as read_only.
429 # A normal string join marks the result as read-only because it contains attributes from joined tables
430 # which are not in the base table and therefore prevent the result from being saved.
431 # In the case of an ar_join, the JoinDependency created to instantiate the results eliminates these
432 # bogus attributes. See JoinDependency#instantiate, and JoinBase#instantiate in associations.rb.
433 validate_find_options(options)
434 set_readonly_option!(options)
437 when :first then find_initial(options)
438 when :all then find_every(options)
439 else find_from_ids(args, options)
443 # Works like find(:all), but requires a complete SQL string. Examples:
444 # Post.find_by_sql "SELECT p.*, c.author FROM posts p, comments c WHERE p.id = c.post_id"
445 # Post.find_by_sql ["SELECT * FROM posts WHERE author = ? AND created > ?", author_id, start_date]
447 connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) }
450 # Returns true if the given +id+ represents the primary key of a record in the database, false otherwise.
451 # You can also pass a set of SQL conditions.
454 # Person.exists?('5')
455 # Person.exists?(:name => "David")
456 # Person.exists?(['name LIKE ?', "%#{query}%"])
457 def exists?(id_or_conditions)
458 !find(:first, :select => "#{table_name}.#{primary_key}", :conditions => expand_id_conditions(id_or_conditions)).nil?
459 rescue ActiveRecord::ActiveRecordError
463 # Creates an object, instantly saves it as a record (if the validation permits it), and returns it. If the save
464 # fails under validations, the unsaved object is still returned.
465 def create(attributes = nil)
466 if attributes.is_a?(Array)
467 attributes.collect { |attr| create(attr) }
469 object = new(attributes)
475 # Finds the record from the passed +id+, instantly saves it with the passed +attributes+ (if the validation permits it),
476 # and returns it. If the save fails under validations, the unsaved object is still returned.
478 # The arguments may also be given as arrays in which case the update method is called for each pair of +id+ and
479 # +attributes+ and an array of objects is returned.
481 # Example of updating one record:
482 # Person.update(15, {:user_name => 'Samuel', :group => 'expert'})
484 # Example of updating multiple records:
485 # people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy"} }
486 # Person.update(people.keys, people.values)
487 def update(id, attributes)
490 id.collect { |id| idx += 1; update(id, attributes[idx]) }
493 object.update_attributes(attributes)
498 # Deletes the record with the given +id+ without instantiating an object first. If an array of ids is provided, all of them
501 delete_all([ "#{connection.quote_column_name(primary_key)} IN (?)", id ])
504 # Destroys the record with the given +id+ by instantiating the object and calling #destroy (all the callbacks are the triggered).
505 # If an array of ids is provided, all of them are destroyed.
507 id.is_a?(Array) ? id.each { |id| destroy(id) } : find(id).destroy
510 # Updates all records with the SET-part of an SQL update statement in +updates+ and returns an integer with the number of rows updated.
511 # A subset of the records can be selected by specifying +conditions+. Example:
512 # Billing.update_all "category = 'authorized', approved = 1", "author = 'David'"
514 # Optional :order and :limit options may be given as the third parameter,
515 # but their behavior is database-specific.
516 def update_all(updates, conditions = nil, options = {})
517 sql = "UPDATE #{table_name} SET #{sanitize_sql_for_assignment(updates)} "
519 add_conditions!(sql, conditions, scope)
520 add_order!(sql, options[:order], scope)
521 add_limit!(sql, options, scope)
522 connection.update(sql, "#{name} Update")
525 # Destroys the objects for all the records that match the +conditions+ by instantiating each object and calling
526 # the destroy method. Example:
527 # Person.destroy_all "last_login < '2004-04-04'"
528 def destroy_all(conditions = nil)
529 find(:all, :conditions => conditions).each { |object| object.destroy }
532 # Deletes all the records that match the +conditions+ without instantiating the objects first (and hence not
533 # calling the destroy method). Example:
534 # Post.delete_all "person_id = 5 AND (category = 'Something' OR category = 'Else')"
535 def delete_all(conditions = nil)
536 sql = "DELETE FROM #{quoted_table_name} "
537 add_conditions!(sql, conditions, scope(:find))
538 connection.delete(sql, "#{name} Delete all")
541 # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
542 # The use of this method should be restricted to complicated SQL queries that can't be executed
543 # using the ActiveRecord::Calculations class methods. Look into those before using this.
547 # +sql+: An SQL statement which should return a count query from the database, see the example below
551 # Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
552 def count_by_sql(sql)
553 sql = sanitize_conditions(sql)
554 connection.select_value(sql, "#{name} Count").to_i
557 # A generic "counter updater" implementation, intended primarily to be
558 # used by increment_counter and decrement_counter, but which may also
559 # be useful on its own. It simply does a direct SQL update for the record
560 # with the given ID, altering the given hash of counters by the amount
561 # given by the corresponding value:
563 # Post.update_counters 5, :comment_count => -1, :action_count => 1
565 # # SET comment_count = comment_count - 1,
566 # # action_count = action_count + 1
568 def update_counters(id, counters)
569 updates = counters.inject([]) { |list, (counter_name, increment)|
570 sign = increment < 0 ? "-" : "+"
571 list << "#{connection.quote_column_name(counter_name)} = #{connection.quote_column_name(counter_name)} #{sign} #{increment.abs}"
573 update_all(updates, "#{connection.quote_column_name(primary_key)} = #{quote_value(id)}")
576 # Increment a number field by one, usually representing a count.
578 # This is used for caching aggregate values, so that they don't need to be computed every time.
579 # For example, a DiscussionBoard may cache post_count and comment_count otherwise every time the board is
580 # shown it would have to run an SQL query to find how many posts and comments there are.
584 # +counter_name+ The name of the field that should be incremented
585 # +id+ The id of the object that should be incremented
589 # # Increment the post_count column for the record with an id of 5
590 # DiscussionBoard.increment_counter(:post_count, 5)
591 def increment_counter(counter_name, id)
592 update_counters(id, counter_name => 1)
595 # Decrement a number field by one, usually representing a count.
597 # This works the same as increment_counter but reduces the column value by 1 instead of increasing it.
601 # +counter_name+ The name of the field that should be decremented
602 # +id+ The id of the object that should be decremented
606 # # Decrement the post_count column for the record with an id of 5
607 # DiscussionBoard.decrement_counter(:post_count, 5)
608 def decrement_counter(counter_name, id)
609 update_counters(id, counter_name => -1)
613 # Attributes named in this macro are protected from mass-assignment, such as <tt>new(attributes)</tt> and
614 # <tt>attributes=(attributes)</tt>. Their assignment will simply be ignored. Instead, you can use the direct writer
615 # methods to do assignment. This is meant to protect sensitive attributes from being overwritten by URL/form hackers. Example:
617 # class Customer < ActiveRecord::Base
618 # attr_protected :credit_rating
621 # customer = Customer.new("name" => David, "credit_rating" => "Excellent")
622 # customer.credit_rating # => nil
623 # customer.attributes = { "description" => "Jolly fellow", "credit_rating" => "Superb" }
624 # customer.credit_rating # => nil
626 # customer.credit_rating = "Average"
627 # customer.credit_rating # => "Average"
629 # To start from an all-closed default and enable attributes as needed, have a look at attr_accessible.
630 def attr_protected(*attributes)
631 write_inheritable_array("attr_protected", attributes - (protected_attributes || []))
634 # Returns an array of all the attributes that have been protected from mass-assignment.
635 def protected_attributes # :nodoc:
636 read_inheritable_attribute("attr_protected")
639 # Similar to the attr_protected macro, this protects attributes of your model from mass-assignment,
640 # such as <tt>new(attributes)</tt> and <tt>attributes=(attributes)</tt>
641 # however, it does it in the opposite way. This locks all attributes and only allows access to the
642 # attributes specified. Assignment to attributes not in this list will be ignored and need to be set
643 # using the direct writer methods instead. This is meant to protect sensitive attributes from being
644 # overwritten by URL/form hackers. If you'd rather start from an all-open default and restrict
645 # attributes as needed, have a look at attr_protected.
649 # <tt>*attributes</tt> A comma separated list of symbols that represent columns _not_ to be protected
653 # class Customer < ActiveRecord::Base
654 # attr_accessible :name, :nickname
657 # customer = Customer.new(:name => "David", :nickname => "Dave", :credit_rating => "Excellent")
658 # customer.credit_rating # => nil
659 # customer.attributes = { :name => "Jolly fellow", :credit_rating => "Superb" }
660 # customer.credit_rating # => nil
662 # customer.credit_rating = "Average"
663 # customer.credit_rating # => "Average"
664 def attr_accessible(*attributes)
665 write_inheritable_array("attr_accessible", attributes - (accessible_attributes || []))
668 # Returns an array of all the attributes that have been made accessible to mass-assignment.
669 def accessible_attributes # :nodoc:
670 read_inheritable_attribute("attr_accessible")
673 # Attributes listed as readonly can be set for a new record, but will be ignored in database updates afterwards.
674 def attr_readonly(*attributes)
675 write_inheritable_array("attr_readonly", attributes - (readonly_attributes || []))
678 # Returns an array of all the attributes that have been specified as readonly.
679 def readonly_attributes
680 read_inheritable_attribute("attr_readonly")
683 # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object,
684 # then specify the name of that attribute using this method and it will be handled automatically.
685 # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that
686 # class on retrieval or +SerializationTypeMismatch+ will be raised.
690 # +attr_name+ The field name that should be serialized
691 # +class_name+ Optional, class name that the object type should be equal to
694 # # Serialize a preferences attribute
696 # serialize :preferences
698 def serialize(attr_name, class_name = Object)
699 serialized_attributes[attr_name.to_s] = class_name
702 # Returns a hash of all the attributes that have been specified for serialization as keys and their class restriction as values.
703 def serialized_attributes
704 read_inheritable_attribute("attr_serialized") or write_inheritable_attribute("attr_serialized", {})
708 # Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending
709 # directly from ActiveRecord. So if the hierarchy looks like: Reply < Message < ActiveRecord, then Message is used
710 # to guess the table name from even when called on Reply. The rules used to do the guess are handled by the Inflector class
711 # in Active Support, which knows almost all common English inflections. You can add new inflections in config/initializers/inflections.rb.
713 # Nested classes are given table names prefixed by the singular form of
714 # the parent's table name. Example:
715 # file class table_name
716 # invoice.rb Invoice invoices
717 # invoice/lineitem.rb Invoice::Lineitem invoice_lineitems
719 # Additionally, the class-level table_name_prefix is prepended and the
720 # table_name_suffix is appended. So if you have "myapp_" as a prefix,
721 # the table name guess for an Invoice class becomes "myapp_invoices".
722 # Invoice::Lineitem becomes "myapp_invoice_lineitems".
724 # You can also overwrite this class method to allow for unguessable
725 # links, such as a Mouse class with a link to a "mice" table. Example:
727 # class Mouse < ActiveRecord::Base
728 # set_table_name "mice"
734 def reset_table_name #:nodoc:
738 # STI subclasses always use their superclass' table.
742 # Nested classes are prefixed with singular parent table name.
743 if parent < ActiveRecord::Base && !parent.abstract_class?
744 contained = parent.table_name
745 contained = contained.singularize if parent.pluralize_table_names
748 name = "#{table_name_prefix}#{contained}#{undecorated_table_name(base.name)}#{table_name_suffix}"
755 # Defines the primary key field -- can be overridden in subclasses. Overwriting will negate any effect of the
756 # primary_key_prefix_type setting, though.
761 def reset_primary_key #:nodoc:
763 case primary_key_prefix_type
765 key = Inflector.foreign_key(base_class.name, false)
766 when :table_name_with_underscore
767 key = Inflector.foreign_key(base_class.name)
773 # Defines the column name for use with single table inheritance
774 # -- can be set in subclasses like so: self.inheritance_column = "type_id"
775 def inheritance_column
776 @inheritance_column ||= "type".freeze
779 # Lazy-set the sequence name to the connection's default. This method
780 # is only ever called once since set_sequence_name overrides it.
781 def sequence_name #:nodoc:
785 def reset_sequence_name #:nodoc:
786 default = connection.default_sequence_name(table_name, primary_key)
787 set_sequence_name(default)
791 # Sets the table name to use to the given value, or (if the value
792 # is nil or false) to the value returned by the given block.
796 # class Project < ActiveRecord::Base
797 # set_table_name "project"
799 def set_table_name(value = nil, &block)
800 define_attr_method :table_name, value, &block
802 alias :table_name= :set_table_name
804 # Sets the name of the primary key column to use to the given value,
805 # or (if the value is nil or false) to the value returned by the given
810 # class Project < ActiveRecord::Base
811 # set_primary_key "sysid"
813 def set_primary_key(value = nil, &block)
814 define_attr_method :primary_key, value, &block
816 alias :primary_key= :set_primary_key
818 # Sets the name of the inheritance column to use to the given value,
819 # or (if the value # is nil or false) to the value returned by the
824 # class Project < ActiveRecord::Base
825 # set_inheritance_column do
826 # original_inheritance_column + "_id"
829 def set_inheritance_column(value = nil, &block)
830 define_attr_method :inheritance_column, value, &block
832 alias :inheritance_column= :set_inheritance_column
834 # Sets the name of the sequence to use when generating ids to the given
835 # value, or (if the value is nil or false) to the value returned by the
836 # given block. This is required for Oracle and is useful for any
837 # database which relies on sequences for primary key generation.
839 # If a sequence name is not explicitly set when using Oracle or Firebird,
840 # it will default to the commonly used pattern of: #{table_name}_seq
842 # If a sequence name is not explicitly set when using PostgreSQL, it
843 # will discover the sequence corresponding to your primary key for you.
847 # class Project < ActiveRecord::Base
848 # set_sequence_name "projectseq" # default would have been "project_seq"
850 def set_sequence_name(value = nil, &block)
851 define_attr_method :sequence_name, value, &block
853 alias :sequence_name= :set_sequence_name
855 # Turns the +table_name+ back into a class name following the reverse rules of +table_name+.
856 def class_name(table_name = table_name) # :nodoc:
857 # remove any prefix and/or suffix from the table name
858 class_name = table_name[table_name_prefix.length..-(table_name_suffix.length + 1)].camelize
859 class_name = class_name.singularize if pluralize_table_names
863 # Indicates whether the table associated with this class exists
865 if connection.respond_to?(:tables)
866 connection.tables.include? table_name
868 # if the connection adapter hasn't implemented tables, there are two crude tests that can be
869 # used - see if getting column info raises an error, or if the number of columns returned is zero
871 reset_column_information
873 rescue ActiveRecord::StatementInvalid
879 # Returns an array of column objects for the table associated with this class.
882 @columns = connection.columns(table_name, "#{name} Columns")
883 @columns.each {|column| column.primary = column.name == primary_key}
888 # Returns a hash of column objects for the table associated with this class.
890 @columns_hash ||= columns.inject({}) { |hash, column| hash[column.name] = column; hash }
893 # Returns an array of column names as strings.
895 @column_names ||= columns.map { |column| column.name }
898 # Returns an array of column objects where the primary id, all columns ending in "_id" or "_count",
899 # and columns used for single table inheritance have been removed.
901 @content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column }
904 # 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
905 # 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
907 def column_methods_hash #:nodoc:
908 @dynamic_methods_hash ||= column_names.inject(Hash.new(false)) do |methods, attr|
909 attr_name = attr.to_s
910 methods[attr.to_sym] = attr_name
911 methods["#{attr}=".to_sym] = attr_name
912 methods["#{attr}?".to_sym] = attr_name
913 methods["#{attr}_before_type_cast".to_sym] = attr_name
918 # Resets all the cached information about columns, which will cause them to be reloaded on the next request.
919 def reset_column_information
920 generated_methods.each { |name| undef_method(name) }
921 @column_names = @columns = @columns_hash = @content_columns = @dynamic_methods_hash = @generated_methods = @inheritance_column = nil
924 def reset_column_information_and_inheritable_attributes_for_all_subclasses#:nodoc:
925 subclasses.each { |klass| klass.reset_inheritable_attributes; klass.reset_column_information }
928 # Transforms attribute key names into a more humane format, such as "First name" instead of "first_name". Example:
929 # Person.human_attribute_name("first_name") # => "First name"
930 # Deprecated in favor of just calling "first_name".humanize
931 def human_attribute_name(attribute_key_name) #:nodoc:
932 attribute_key_name.humanize
935 # True if this isn't a concrete subclass needing a STI type condition.
936 def descends_from_active_record?
937 if superclass.abstract_class?
938 superclass.descends_from_active_record?
940 superclass == Base || !columns_hash.include?(inheritance_column)
944 def finder_needs_type_condition? #:nodoc:
945 # This is like this because benchmarking justifies the strange :false stuff
946 :true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true)
949 # Returns a string like 'Post id:integer, title:string, body:text'
953 elsif abstract_class?
956 attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', '
957 "#{super}(#{attr_list})"
959 "#{super}(Table doesn't exist)"
964 def quote_value(value, column = nil) #:nodoc:
965 connection.quote(value,column)
968 # Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>.
969 def sanitize(object) #:nodoc:
970 connection.quote(object)
973 # Log and benchmark multiple statements in a single block. Example:
975 # Project.benchmark("Creating project") do
976 # project = Project.create("name" => "stuff")
977 # project.create_manager("name" => "David")
978 # project.milestones << Milestone.find(:all)
981 # The benchmark is only recorded if the current level of the logger matches the <tt>log_level</tt>, which makes it
982 # easy to include benchmarking statements in production software that will remain inexpensive because the benchmark
983 # will only be conducted if the log level is low enough.
985 # The logging of the multiple statements is turned off unless <tt>use_silence</tt> is set to false.
986 def benchmark(title, log_level = Logger::DEBUG, use_silence = true)
987 if logger && logger.level == log_level
989 seconds = Benchmark.realtime { result = use_silence ? silence { yield } : yield }
990 logger.add(log_level, "#{title} (#{'%.5f' % seconds})")
997 # Silences the logger for the duration of the block.
999 old_logger_level, logger.level = logger.level, Logger::ERROR if logger
1002 logger.level = old_logger_level if logger
1005 # Overwrite the default class equality method to provide support for association proxies.
1010 # Returns the base AR subclass that this class descends from. If A
1011 # extends AR::Base, A.base_class will return A. If B descends from A
1012 # through some arbitrarily deep hierarchy, B.base_class will return A.
1014 class_of_active_record_descendant(self)
1017 # Set this to true if this is an abstract class (see #abstract_class?).
1018 attr_accessor :abstract_class
1020 # Returns whether this class is a base AR class. If A is a base class and
1021 # B descends from A, then B.base_class will return B.
1023 abstract_class == true
1027 def find_initial(options)
1028 options.update(:limit => 1) unless options[:include]
1029 find_every(options).first
1032 def find_every(options)
1033 records = scoped?(:find, :include) || options[:include] ?
1034 find_with_associations(options) :
1035 find_by_sql(construct_finder_sql(options))
1037 records.each { |record| record.readonly! } if options[:readonly]
1042 def find_from_ids(ids, options)
1043 expects_array = ids.first.kind_of?(Array)
1044 return ids.first if expects_array && ids.first.empty?
1046 ids = ids.flatten.compact.uniq
1050 raise RecordNotFound, "Couldn't find #{name} without an ID"
1052 result = find_one(ids.first, options)
1053 expects_array ? [ result ] : result
1055 find_some(ids, options)
1059 def find_one(id, options)
1060 conditions = " AND (#{sanitize_sql(options[:conditions])})" if options[:conditions]
1061 options.update :conditions => "#{quoted_table_name}.#{connection.quote_column_name(primary_key)} = #{quote_value(id,columns_hash[primary_key])}#{conditions}"
1063 # Use find_every(options).first since the primary key condition
1064 # already ensures we have a single record. Using find_initial adds
1065 # a superfluous :limit => 1.
1066 if result = find_every(options).first
1069 raise RecordNotFound, "Couldn't find #{name} with ID=#{id}#{conditions}"
1073 def find_some(ids, options)
1074 conditions = " AND (#{sanitize_sql(options[:conditions])})" if options[:conditions]
1075 ids_list = ids.map { |id| quote_value(id,columns_hash[primary_key]) }.join(',')
1076 options.update :conditions => "#{quoted_table_name}.#{connection.quote_column_name(primary_key)} IN (#{ids_list})#{conditions}"
1078 result = find_every(options)
1080 # Determine expected size from limit and offset, not just ids.size.
1082 if options[:limit] && ids.size > options[:limit]
1088 # 11 ids with limit 3, offset 9 should give 2 results.
1089 if options[:offset] && (ids.size - options[:offset] < expected_size)
1090 expected_size = ids.size - options[:offset]
1093 if result.size == expected_size
1096 raise RecordNotFound, "Couldn't find all #{name.pluralize} with IDs (#{ids_list})#{conditions} (found #{result.size} results, but was looking for #{expected_size})"
1100 # Finder methods must instantiate through this method to work with the
1101 # single-table inheritance model that makes it possible to create
1102 # objects of different types from the same table.
1103 def instantiate(record)
1105 if subclass_name = record[inheritance_column]
1107 if subclass_name.empty?
1111 # Ignore type if no column is present since it was probably
1112 # pulled in from a sloppy join.
1113 unless columns_hash.include?(inheritance_column)
1118 compute_type(subclass_name).allocate
1120 raise SubclassNotFound,
1121 "The single-table inheritance mechanism failed to locate the subclass: '#{record[inheritance_column]}'. " +
1122 "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " +
1123 "Please rename this column if you didn't intend it to be used for storing the inheritance class " +
1124 "or overwrite #{self.to_s}.inheritance_column to use another column for that information."
1132 object.instance_variable_set("@attributes", record)
1133 object.instance_variable_set("@attributes_cache", Hash.new)
1135 if object.respond_to_without_attributes?(:after_find)
1136 object.send(:callback, :after_find)
1139 if object.respond_to_without_attributes?(:after_initialize)
1140 object.send(:callback, :after_initialize)
1146 # Nest the type name in the same module as this class.
1147 # Bar is "MyApp::Business::Bar" relative to MyApp::Business::Foo
1148 def type_name_with_module(type_name)
1149 (/^::/ =~ type_name) ? type_name : "#{parent.name}::#{type_name}"
1152 def construct_finder_sql(options)
1153 scope = scope(:find)
1154 sql = "SELECT #{(scope && scope[:select]) || options[:select] || (options[:joins] && quoted_table_name + '.*') || '*'} "
1155 sql << "FROM #{(scope && scope[:from]) || options[:from] || quoted_table_name} "
1157 add_joins!(sql, options, scope)
1158 add_conditions!(sql, options[:conditions], scope)
1160 add_group!(sql, options[:group], scope)
1161 add_order!(sql, options[:order], scope)
1162 add_limit!(sql, options, scope)
1163 add_lock!(sql, options, scope)
1168 # Merges includes so that the result is a valid +include+
1169 def merge_includes(first, second)
1170 (safe_to_array(first) + safe_to_array(second)).uniq
1173 # Object#to_a is deprecated, though it does have the desired behavior
1174 def safe_to_array(o)
1185 def add_order!(sql, order, scope = :auto)
1186 scope = scope(:find) if :auto == scope
1187 scoped_order = scope[:order] if scope
1189 sql << " ORDER BY #{order}"
1190 sql << ", #{scoped_order}" if scoped_order
1192 sql << " ORDER BY #{scoped_order}" if scoped_order
1196 def add_group!(sql, group, scope = :auto)
1198 sql << " GROUP BY #{group}"
1200 scope = scope(:find) if :auto == scope
1201 if scope && (scoped_group = scope[:group])
1202 sql << " GROUP BY #{scoped_group}"
1207 # The optional scope argument is for the current :find scope.
1208 def add_limit!(sql, options, scope = :auto)
1209 scope = scope(:find) if :auto == scope
1212 options[:limit] ||= scope[:limit]
1213 options[:offset] ||= scope[:offset]
1216 connection.add_limit_offset!(sql, options)
1219 # The optional scope argument is for the current :find scope.
1220 # The :lock option has precedence over a scoped :lock.
1221 def add_lock!(sql, options, scope = :auto)
1222 scope = scope(:find) if :auto == scope
1223 options = options.reverse_merge(:lock => scope[:lock]) if scope
1224 connection.add_lock!(sql, options)
1227 # The optional scope argument is for the current :find scope.
1228 def add_joins!(sql, options, scope = :auto)
1229 scope = scope(:find) if :auto == scope
1230 join = (scope && scope[:joins]) || options[:joins]
1232 when Symbol, Hash, Array
1233 join_dependency = ActiveRecord::Associations::ClassMethods::InnerJoinDependency.new(self, join, nil)
1234 sql << " #{join_dependency.join_associations.collect{|join| join.association_join }.join} "
1240 # Adds a sanitized version of +conditions+ to the +sql+ string. Note that the passed-in +sql+ string is changed.
1241 # The optional scope argument is for the current :find scope.
1242 def add_conditions!(sql, conditions, scope = :auto)
1243 scope = scope(:find) if :auto == scope
1245 segments << sanitize_sql(scope[:conditions]) if scope && !scope[:conditions].blank?
1246 segments << sanitize_sql(conditions) unless conditions.blank?
1247 segments << type_condition if finder_needs_type_condition?
1248 segments.delete_if{|s| s.blank?}
1249 sql << "WHERE (#{segments.join(") AND (")}) " unless segments.empty?
1253 quoted_inheritance_column = connection.quote_column_name(inheritance_column)
1254 type_condition = subclasses.inject("#{quoted_table_name}.#{quoted_inheritance_column} = '#{name.demodulize}' ") do |condition, subclass|
1255 condition << "OR #{quoted_table_name}.#{quoted_inheritance_column} = '#{subclass.name.demodulize}' "
1258 " (#{type_condition}) "
1261 # Guesses the table name, but does not decorate it with prefix and suffix information.
1262 def undecorated_table_name(class_name = base_class.name)
1263 table_name = Inflector.underscore(Inflector.demodulize(class_name))
1264 table_name = Inflector.pluralize(table_name) if pluralize_table_names
1268 # Enables dynamic finders like find_by_user_name(user_name) and find_by_user_name_and_password(user_name, password) that are turned into
1269 # find(:first, :conditions => ["user_name = ?", user_name]) and find(:first, :conditions => ["user_name = ? AND password = ?", user_name, password])
1270 # respectively. Also works for find(:all) by using find_all_by_amount(50) that is turned into find(:all, :conditions => ["amount = ?", 50]).
1272 # It's even possible to use all the additional parameters to find. For example, the full interface for find_all_by_amount
1273 # is actually find_all_by_amount(amount, options).
1275 # This also enables you to initialize a record if it is not found, such as find_or_initialize_by_amount(amount)
1276 # or find_or_create_by_user_and_password(user, password).
1278 # Each dynamic finder or initializer/creator is also defined in the class after it is first invoked, so that future
1279 # attempts to use it do not run through method_missing.
1280 def method_missing(method_id, *arguments)
1281 if match = /^find_(all_by|by)_([_a-zA-Z]\w*)$/.match(method_id.to_s)
1282 finder = determine_finder(match)
1284 attribute_names = extract_attribute_names_from_match(match)
1285 super unless all_attributes_exists?(attribute_names)
1288 def self.#{method_id}(*args)
1289 options = args.last.is_a?(Hash) ? args.pop : {}
1290 attributes = construct_attributes_from_arguments([:#{attribute_names.join(',:')}], args)
1291 finder_options = { :conditions => attributes }
1292 validate_find_options(options)
1293 set_readonly_option!(options)
1295 if options[:conditions]
1296 with_scope(:find => finder_options) do
1297 ActiveSupport::Deprecation.silence { send(:#{finder}, options) }
1300 ActiveSupport::Deprecation.silence { send(:#{finder}, options.merge(finder_options)) }
1303 }, __FILE__, __LINE__
1304 send(method_id, *arguments)
1305 elsif match = /^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/.match(method_id.to_s)
1306 instantiator = determine_instantiator(match)
1307 attribute_names = extract_attribute_names_from_match(match)
1308 super unless all_attributes_exists?(attribute_names)
1311 def self.#{method_id}(*args)
1312 if args[0].is_a?(Hash)
1313 attributes = args[0].with_indifferent_access
1314 find_attributes = attributes.slice(*[:#{attribute_names.join(',:')}])
1316 find_attributes = attributes = construct_attributes_from_arguments([:#{attribute_names.join(',:')}], args)
1319 options = { :conditions => find_attributes }
1320 set_readonly_option!(options)
1322 record = find_initial(options)
1324 record = self.new { |r| r.send(:attributes=, attributes, false) }
1325 #{'record.save' if instantiator == :create}
1331 }, __FILE__, __LINE__
1332 send(method_id, *arguments)
1338 def determine_finder(match)
1339 match.captures.first == 'all_by' ? :find_every : :find_initial
1342 def determine_instantiator(match)
1343 match.captures.first == 'initialize' ? :new : :create
1346 def extract_attribute_names_from_match(match)
1347 match.captures.last.split('_and_')
1350 def construct_attributes_from_arguments(attribute_names, arguments)
1352 attribute_names.each_with_index { |name, idx| attributes[name] = arguments[idx] }
1356 def all_attributes_exists?(attribute_names)
1357 attribute_names.all? { |name| column_methods_hash.include?(name.to_sym) }
1360 def attribute_condition(argument)
1362 when nil then "IS ?"
1363 when Array, ActiveRecord::Associations::AssociationCollection then "IN (?)"
1364 when Range then "BETWEEN ? AND ?"
1369 # Interpret Array and Hash as conditions and anything else as an id.
1370 def expand_id_conditions(id_or_conditions)
1371 case id_or_conditions
1372 when Array, Hash then id_or_conditions
1373 else sanitize_sql(primary_key => id_or_conditions)
1378 # Defines an "attribute" method (like #inheritance_column or
1379 # #table_name). A new (class) method will be created with the
1380 # given name. If a value is specified, the new method will
1381 # return that value (as a string). Otherwise, the given block
1382 # will be used to compute the value of the method.
1384 # The original method will be aliased, with the new name being
1385 # prefixed with "original_". This allows the new method to
1386 # access the original value.
1390 # class A < ActiveRecord::Base
1391 # define_attr_method :primary_key, "sysid"
1392 # define_attr_method( :inheritance_column ) do
1393 # original_inheritance_column + "_id"
1396 def define_attr_method(name, value=nil, &block)
1397 sing = class << self; self; end
1398 sing.send :alias_method, "original_#{name}", name
1400 sing.send :define_method, name, &block
1402 # use eval instead of a block to work around a memory leak in dev
1404 sing.class_eval "def #{name}; #{value.to_s.inspect}; end"
1409 # Scope parameters to method calls within the block. Takes a hash of method_name => parameters hash.
1410 # method_name may be :find or :create. :find parameters may include the <tt>:conditions</tt>, <tt>:joins</tt>,
1411 # <tt>:include</tt>, <tt>:offset</tt>, <tt>:limit</tt>, and <tt>:readonly</tt> options. :create parameters are an attributes hash.
1413 # class Article < ActiveRecord::Base
1414 # def self.create_with_scope
1415 # with_scope(:find => { :conditions => "blog_id = 1" }, :create => { :blog_id => 1 }) do
1416 # find(1) # => SELECT * from articles WHERE blog_id = 1 AND id = 1
1423 # In nested scopings, all previous parameters are overwritten by the innermost rule, with the exception of
1424 # :conditions and :include options in :find, which are merged.
1426 # class Article < ActiveRecord::Base
1427 # def self.find_with_scope
1428 # with_scope(:find => { :conditions => "blog_id = 1", :limit => 1 }, :create => { :blog_id => 1 }) do
1429 # with_scope(:find => { :limit => 10})
1430 # find(:all) # => SELECT * from articles WHERE blog_id = 1 LIMIT 10
1432 # with_scope(:find => { :conditions => "author_id = 3" })
1433 # find(:all) # => SELECT * from articles WHERE blog_id = 1 AND author_id = 3 LIMIT 1
1439 # You can ignore any previous scopings by using the <tt>with_exclusive_scope</tt> method.
1441 # class Article < ActiveRecord::Base
1442 # def self.find_with_exclusive_scope
1443 # with_scope(:find => { :conditions => "blog_id = 1", :limit => 1 }) do
1444 # with_exclusive_scope(:find => { :limit => 10 })
1445 # find(:all) # => SELECT * from articles LIMIT 10
1450 def with_scope(method_scoping = {}, action = :merge, &block)
1451 method_scoping = method_scoping.method_scoping if method_scoping.respond_to?(:method_scoping)
1453 # Dup first and second level of hash (method and params).
1454 method_scoping = method_scoping.inject({}) do |hash, (method, params)|
1455 hash[method] = (params == true) ? params : params.dup
1459 method_scoping.assert_valid_keys([ :find, :create ])
1461 if f = method_scoping[:find]
1462 f.assert_valid_keys(VALID_FIND_OPTIONS)
1463 set_readonly_option! f
1467 if action == :merge && current_scoped_methods
1468 method_scoping = current_scoped_methods.inject(method_scoping) do |hash, (method, params)|
1472 (hash[method].keys + params.keys).uniq.each do |key|
1473 merge = hash[method][key] && params[key] # merge if both scopes have the same key
1474 if key == :conditions && merge
1475 hash[method][key] = [params[key], hash[method][key]].collect{ |sql| "( %s )" % sanitize_sql(sql) }.join(" AND ")
1476 elsif key == :include && merge
1477 hash[method][key] = merge_includes(hash[method][key], params[key]).uniq
1479 hash[method][key] = hash[method][key] || params[key]
1483 hash[method] = params.merge(hash[method])
1486 hash[method] = params
1492 self.scoped_methods << method_scoping
1497 self.scoped_methods.pop
1501 # Works like with_scope, but discards any nested properties.
1502 def with_exclusive_scope(method_scoping = {}, &block)
1503 with_scope(method_scoping, :overwrite, &block)
1506 def subclasses #:nodoc:
1507 @@subclasses[self] ||= []
1508 @@subclasses[self] + extra = @@subclasses[self].inject([]) {|list, subclass| list + subclass.subclasses }
1511 # Test whether the given method and optional key are scoped.
1512 def scoped?(method, key = nil) #:nodoc:
1513 if current_scoped_methods && (scope = current_scoped_methods[method])
1514 !key || scope.has_key?(key)
1518 # Retrieve the scope for the given method and optional key.
1519 def scope(method, key = nil) #:nodoc:
1520 if current_scoped_methods && (scope = current_scoped_methods[method])
1521 key ? scope[key] : scope
1525 def thread_safe_scoped_methods #:nodoc:
1526 scoped_methods = (Thread.current[:scoped_methods] ||= {})
1527 scoped_methods[self] ||= []
1530 def single_threaded_scoped_methods #:nodoc:
1531 @scoped_methods ||= []
1534 # pick up the correct scoped_methods version from @@allow_concurrency
1535 if @@allow_concurrency
1536 alias_method :scoped_methods, :thread_safe_scoped_methods
1538 alias_method :scoped_methods, :single_threaded_scoped_methods
1541 def current_scoped_methods #:nodoc:
1545 # Returns the class type of the record using the current module as a prefix. So descendents of
1546 # MyApp::Business::Account would appear as MyApp::Business::AccountSubclass.
1547 def compute_type(type_name)
1548 modularized_name = type_name_with_module(type_name)
1550 class_eval(modularized_name, __FILE__, __LINE__)
1552 class_eval(type_name, __FILE__, __LINE__)
1556 # Returns the class descending directly from ActiveRecord in the inheritance hierarchy.
1557 def class_of_active_record_descendant(klass)
1558 if klass.superclass == Base || klass.superclass.abstract_class?
1560 elsif klass.superclass.nil?
1561 raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord"
1563 class_of_active_record_descendant(klass.superclass)
1567 # Returns the name of the class descending directly from ActiveRecord in the inheritance hierarchy.
1568 def class_name_of_active_record_descendant(klass) #:nodoc:
1569 klass.base_class.name
1572 # Accepts an array, hash, or string of sql conditions and sanitizes
1573 # them into a valid SQL fragment for a WHERE clause.
1574 # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
1575 # { :name => "foo'bar", :group_id => 4 } returns "name='foo''bar' and group_id='4'"
1576 # "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'"
1577 def sanitize_sql_for_conditions(condition)
1579 when Array; sanitize_sql_array(condition)
1580 when Hash; sanitize_sql_hash_for_conditions(condition)
1584 alias_method :sanitize_sql, :sanitize_sql_for_conditions
1586 # Accepts an array, hash, or string of sql conditions and sanitizes
1587 # them into a valid SQL fragment for a SET clause.
1588 # { :name => nil, :group_id => 4 } returns "name = NULL , group_id='4'"
1589 def sanitize_sql_for_assignment(assignments)
1591 when Array; sanitize_sql_array(assignments)
1592 when Hash; sanitize_sql_hash_for_assignment(assignments)
1597 # Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause.
1598 # { :name => "foo'bar", :group_id => 4 }
1599 # # => "name='foo''bar' and group_id= 4"
1600 # { :status => nil, :group_id => [1,2,3] }
1601 # # => "status IS NULL and group_id IN (1,2,3)"
1602 # { :age => 13..18 }
1603 # # => "age BETWEEN 13 AND 18"
1604 # { 'other_records.id' => 7 }
1605 # # => "`other_records`.`id` = 7"
1606 def sanitize_sql_hash_for_conditions(attrs)
1607 conditions = attrs.map do |attr, value|
1610 # Extract table name from qualified attribute names.
1611 if attr.include?('.')
1612 table_name, attr = attr.split('.', 2)
1613 table_name = connection.quote_table_name(table_name)
1615 table_name = quoted_table_name
1618 "#{table_name}.#{connection.quote_column_name(attr)} #{attribute_condition(value)}"
1621 replace_bind_variables(conditions, expand_range_bind_variables(attrs.values))
1623 alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions
1625 # Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause.
1626 # { :status => nil, :group_id => 1 }
1627 # # => "status = NULL , group_id = 1"
1628 def sanitize_sql_hash_for_assignment(attrs)
1629 conditions = attrs.map do |attr, value|
1630 "#{connection.quote_column_name(attr)} = #{quote_bound_value(value)}"
1634 # Accepts an array of conditions. The array has each value
1635 # sanitized and interpolated into the sql statement.
1636 # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
1637 def sanitize_sql_array(ary)
1638 statement, *values = ary
1639 if values.first.is_a?(Hash) and statement =~ /:\w+/
1640 replace_named_bind_variables(statement, values.first)
1641 elsif statement.include?('?')
1642 replace_bind_variables(statement, values)
1644 statement % values.collect { |value| connection.quote_string(value.to_s) }
1648 alias_method :sanitize_conditions, :sanitize_sql
1650 def replace_bind_variables(statement, values) #:nodoc:
1651 raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size)
1653 statement.gsub('?') { quote_bound_value(bound.shift) }
1656 def replace_named_bind_variables(statement, bind_vars) #:nodoc:
1657 statement.gsub(/:(\w+)/) do
1659 if bind_vars.include?(match)
1660 quote_bound_value(bind_vars[match])
1662 raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}"
1667 def expand_range_bind_variables(bind_vars) #:nodoc:
1668 bind_vars.each_with_index do |var, index|
1669 bind_vars[index, 1] = [var.first, var.last] if var.is_a?(Range)
1674 def quote_bound_value(value) #:nodoc:
1675 if value.respond_to?(:map) && !value.is_a?(String)
1676 if value.respond_to?(:empty?) && value.empty?
1677 connection.quote(nil)
1679 value.map { |v| connection.quote(v) }.join(',')
1682 connection.quote(value)
1686 def raise_if_bind_arity_mismatch(statement, expected, provided) #:nodoc:
1687 unless expected == provided
1688 raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}"
1692 VALID_FIND_OPTIONS = [ :conditions, :include, :joins, :limit, :offset,
1693 :order, :select, :readonly, :group, :from, :lock ]
1695 def validate_find_options(options) #:nodoc:
1696 options.assert_valid_keys(VALID_FIND_OPTIONS)
1699 def set_readonly_option!(options) #:nodoc:
1700 # Inherit :readonly from finder scope if set. Otherwise,
1701 # if :joins is not blank then :readonly defaults to true.
1702 unless options.has_key?(:readonly)
1703 if scoped_readonly = scope(:find, :readonly)
1704 options[:readonly] = scoped_readonly
1705 elsif !options[:joins].blank? && !options[:select]
1706 options[:readonly] = true
1711 def encode_quoted_value(value) #:nodoc:
1712 quoted_value = connection.quote(value)
1713 quoted_value = "'#{quoted_value[1..-2].gsub(/\'/, "\\\\'")}'" if quoted_value.include?("\\\'") # (for ruby mode) "
1719 # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
1720 # attributes but not yet saved (pass a hash with key names matching the associated table column names).
1721 # In both instances, valid attribute keys are determined by the column names of the associated table --
1722 # hence you can't have attributes that aren't part of the table columns.
1723 def initialize(attributes = nil)
1724 @attributes = attributes_from_column_definition
1725 @attributes_cache = {}
1728 self.attributes = attributes unless attributes.nil?
1729 self.class.send(:scope, :create).each { |att,value| self.send("#{att}=", value) } if self.class.send(:scoped?, :create)
1730 result = yield self if block_given?
1731 callback(:after_initialize) if respond_to_without_attributes?(:after_initialize)
1735 # A model instance's primary key is always available as model.id
1736 # whether you name it the default 'id' or set it to something else.
1738 attr_name = self.class.primary_key
1739 column = column_for_attribute(attr_name)
1741 self.class.send(:define_read_method, :id, attr_name, column)
1742 # now that the method exists, call it
1743 self.send attr_name.to_sym
1747 # Enables Active Record objects to be used as URL parameters in Action Pack automatically.
1749 # We can't use alias_method here, because method 'id' optimizes itself on the fly.
1750 (id = self.id) ? id.to_s : nil # Be sure to stringify the id for routes
1753 def id_before_type_cast #:nodoc:
1754 read_attribute_before_type_cast(self.class.primary_key)
1757 def quoted_id #:nodoc:
1758 quote_value(id, column_for_attribute(self.class.primary_key))
1761 # Sets the primary ID.
1763 write_attribute(self.class.primary_key, value)
1766 # Returns true if this object hasn't been saved yet -- that is, a record for the object doesn't exist yet.
1771 # * No record exists: Creates a new record with values matching those of the object attributes.
1772 # * A record does exist: Updates the record with values matching those of the object attributes.
1777 # Attempts to save the record, but instead of just returning false if it couldn't happen, it raises a
1778 # RecordNotSaved exception
1780 create_or_update || raise(RecordNotSaved)
1783 # Deletes the record in the database and freezes this instance to reflect that no changes should
1784 # be made (since they can't be persisted).
1787 connection.delete <<-end_sql, "#{self.class.name} Destroy"
1788 DELETE FROM #{self.class.quoted_table_name}
1789 WHERE #{connection.quote_column_name(self.class.primary_key)} = #{quoted_id}
1796 # Returns a clone of the record that hasn't been assigned an id yet and
1797 # is treated as a new record. Note that this is a "shallow" clone:
1798 # it copies the object's attributes only, not its associations.
1799 # The extent of a "deep" clone is application-specific and is therefore
1800 # left to the application to implement according to its need.
1802 attrs = self.attributes_before_type_cast
1803 attrs.delete(self.class.primary_key)
1804 record = self.class.new
1805 record.send :instance_variable_set, '@attributes', attrs
1809 # Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records.
1810 # Note: This method is overwritten by the Validation module that'll make sure that updates made with this method
1811 # aren't subjected to validation checks. Hence, attributes can be updated even if the full object isn't valid.
1812 def update_attribute(name, value)
1813 send(name.to_s + '=', value)
1817 # Updates all the attributes from the passed-in Hash and saves the record. If the object is invalid, the saving will
1818 # fail and false will be returned.
1819 def update_attributes(attributes)
1820 self.attributes = attributes
1824 # Updates an object just like Base.update_attributes but calls save! instead of save so an exception is raised if the record is invalid.
1825 def update_attributes!(attributes)
1826 self.attributes = attributes
1830 # Initializes the +attribute+ to zero if nil and adds one. Only makes sense for number-based attributes. Returns self.
1831 def increment(attribute)
1832 self[attribute] ||= 0
1833 self[attribute] += 1
1837 # Increments the +attribute+ and saves the record.
1838 def increment!(attribute)
1839 increment(attribute).update_attribute(attribute, self[attribute])
1842 # Initializes the +attribute+ to zero if nil and subtracts one. Only makes sense for number-based attributes. Returns self.
1843 def decrement(attribute)
1844 self[attribute] ||= 0
1845 self[attribute] -= 1
1849 # Decrements the +attribute+ and saves the record.
1850 def decrement!(attribute)
1851 decrement(attribute).update_attribute(attribute, self[attribute])
1854 # Turns an +attribute+ that's currently true into false and vice versa. Returns self.
1855 def toggle(attribute)
1856 self[attribute] = !send("#{attribute}?")
1860 # Toggles the +attribute+ and saves the record.
1861 def toggle!(attribute)
1862 toggle(attribute).update_attribute(attribute, self[attribute])
1865 # Reloads the attributes of this object from the database.
1866 # The optional options argument is passed to find when reloading so you
1867 # may do e.g. record.reload(:lock => true) to reload the same record with
1868 # an exclusive row lock.
1869 def reload(options = nil)
1870 clear_aggregation_cache
1871 clear_association_cache
1872 @attributes.update(self.class.find(self.id, options).instance_variable_get('@attributes'))
1873 @attributes_cache = {}
1877 # Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
1878 # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
1879 # (Alias for the protected read_attribute method).
1881 read_attribute(attr_name)
1884 # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
1885 # (Alias for the protected write_attribute method).
1886 def []=(attr_name, value)
1887 write_attribute(attr_name, value)
1890 # Allows you to set all the attributes at once by passing in a hash with keys
1891 # matching the attribute names (which again matches the column names). Sensitive attributes can be protected
1892 # from this form of mass-assignment by using the +attr_protected+ macro. Or you can alternatively
1893 # specify which attributes *can* be accessed with the +attr_accessible+ macro. Then all the
1894 # attributes not included in that won't be allowed to be mass-assigned.
1895 def attributes=(new_attributes, guard_protected_attributes = true)
1896 return if new_attributes.nil?
1897 attributes = new_attributes.dup
1898 attributes.stringify_keys!
1900 multi_parameter_attributes = []
1901 attributes = remove_attributes_protected_from_mass_assignment(attributes) if guard_protected_attributes
1903 attributes.each do |k, v|
1904 k.include?("(") ? multi_parameter_attributes << [ k, v ] : send(k + "=", v)
1907 assign_multiparameter_attributes(multi_parameter_attributes)
1911 # Returns a hash of all the attributes with their names as keys and clones of their objects as values.
1912 def attributes(options = nil)
1913 attributes = clone_attributes :read_attribute
1918 if except = options[:except]
1919 except = Array(except).collect { |attribute| attribute.to_s }
1920 except.each { |attribute_name| attributes.delete(attribute_name) }
1922 elsif only = options[:only]
1923 only = Array(only).collect { |attribute| attribute.to_s }
1924 attributes.delete_if { |key, value| !only.include?(key) }
1927 raise ArgumentError, "Options does not specify :except or :only (#{options.keys.inspect})"
1932 # Returns a hash of cloned attributes before typecasting and deserialization.
1933 def attributes_before_type_cast
1934 clone_attributes :read_attribute_before_type_cast
1937 # Format attributes nicely for inspect.
1938 def attribute_for_inspect(attr_name)
1939 value = read_attribute(attr_name)
1941 if value.is_a?(String) && value.length > 50
1942 %("#{value[0..50]}...")
1943 elsif value.is_a?(Date) || value.is_a?(Time)
1944 %("#{value.to_s(:db)}")
1950 # Returns true if the specified +attribute+ has been set by the user or by a database load and is neither
1951 # nil nor empty? (the latter only applies to objects that respond to empty?, most notably Strings).
1952 def attribute_present?(attribute)
1953 value = read_attribute(attribute)
1957 # Returns true if the given attribute is in the attributes hash
1958 def has_attribute?(attr_name)
1959 @attributes.has_key?(attr_name.to_s)
1962 # Returns an array of names for the attributes available on this object sorted alphabetically.
1964 @attributes.keys.sort
1967 # Returns the column object for the named attribute.
1968 def column_for_attribute(name)
1969 self.class.columns_hash[name.to_s]
1972 # Returns true if the +comparison_object+ is the same object, or is of the same type and has the same id.
1973 def ==(comparison_object)
1974 comparison_object.equal?(self) ||
1975 (comparison_object.instance_of?(self.class) &&
1976 comparison_object.id == id &&
1977 !comparison_object.new_record?)
1981 def eql?(comparison_object)
1982 self == (comparison_object)
1985 # Delegates to id in order to allow two records of the same type and id to work with something like:
1986 # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
1991 # Just freeze the attributes hash, such that associations are still accessible even on destroyed records.
1993 @attributes.freeze; self
2000 # Records loaded through joins with piggy-back attributes will be marked as read only as they cannot be saved and return true to this query.
2005 def readonly! #:nodoc:
2009 # Nice pretty inspect.
2011 attributes_as_nice_string = self.class.column_names.collect { |name|
2012 if has_attribute?(name) || new_record?
2013 "#{name}: #{attribute_for_inspect(name)}"
2015 }.compact.join(", ")
2016 "#<#{self.class} #{attributes_as_nice_string}>"
2020 def create_or_update
2021 raise ReadOnlyRecord if readonly?
2022 result = new_record? ? create : update
2026 # Updates the associated record with values matching those of the instance attributes.
2027 # Returns the number of affected rows.
2029 quoted_attributes = attributes_with_quotes(false, false)
2030 return 0 if quoted_attributes.empty?
2032 "UPDATE #{self.class.quoted_table_name} " +
2033 "SET #{quoted_comma_pair_list(connection, quoted_attributes)} " +
2034 "WHERE #{connection.quote_column_name(self.class.primary_key)} = #{quote_value(id)}",
2035 "#{self.class.name} Update"
2039 # Creates a record with values matching those of the instance attributes
2040 # and returns its id.
2042 if self.id.nil? && connection.prefetch_primary_key?(self.class.table_name)
2043 self.id = connection.next_sequence_value(self.class.sequence_name)
2046 quoted_attributes = attributes_with_quotes
2048 statement = if quoted_attributes.empty?
2049 connection.empty_insert_statement(self.class.table_name)
2051 "INSERT INTO #{self.class.quoted_table_name} " +
2052 "(#{quoted_column_names.join(', ')}) " +
2053 "VALUES(#{quoted_attributes.values.join(', ')})"
2056 self.id = connection.insert(statement, "#{self.class.name} Create",
2057 self.class.primary_key, self.id, self.class.sequence_name)
2063 # Sets the attribute used for single table inheritance to this class name if this is not the ActiveRecord descendent.
2064 # Considering the hierarchy Reply < Message < ActiveRecord, this makes it possible to do Reply.new without having to
2065 # set Reply[Reply.inheritance_column] = "Reply" yourself. No such attribute would be set for objects of the
2066 # Message class in that example.
2067 def ensure_proper_type
2068 unless self.class.descends_from_active_record?
2069 write_attribute(self.class.inheritance_column, Inflector.demodulize(self.class.name))
2073 def convert_number_column_value(value)
2082 def remove_attributes_protected_from_mass_assignment(attributes)
2084 if self.class.accessible_attributes.nil? && self.class.protected_attributes.nil?
2085 attributes.reject { |key, value| attributes_protected_by_default.include?(key.gsub(/\(.+/, "")) }
2086 elsif self.class.protected_attributes.nil?
2087 attributes.reject { |key, value| !self.class.accessible_attributes.include?(key.gsub(/\(.+/, "").intern) || attributes_protected_by_default.include?(key.gsub(/\(.+/, "")) }
2088 elsif self.class.accessible_attributes.nil?
2089 attributes.reject { |key, value| self.class.protected_attributes.include?(key.gsub(/\(.+/,"").intern) || attributes_protected_by_default.include?(key.gsub(/\(.+/, "")) }
2091 raise "Declare either attr_protected or attr_accessible for #{self.class}, but not both."
2094 removed_attributes = attributes.keys - safe_attributes.keys
2096 if removed_attributes.any?
2097 logger.debug "WARNING: Can't mass-assign these protected attributes: #{removed_attributes.join(', ')}"
2103 # Removes attributes which have been marked as readonly.
2104 def remove_readonly_attributes(attributes)
2105 unless self.class.readonly_attributes.nil?
2106 attributes.delete_if { |key, value| self.class.readonly_attributes.include?(key.gsub(/\(.+/,"").intern) }
2112 # The primary key and inheritance column can never be set by mass-assignment for security reasons.
2113 def attributes_protected_by_default
2114 default = [ self.class.primary_key, self.class.inheritance_column ]
2115 default << 'id' unless self.class.primary_key.eql? 'id'
2119 # Returns a copy of the attributes hash where all the values have been safely quoted for use in
2121 def attributes_with_quotes(include_primary_key = true, include_readonly_attributes = true)
2122 quoted = attributes.inject({}) do |quoted, (name, value)|
2123 if column = column_for_attribute(name)
2124 quoted[name] = quote_value(value, column) unless !include_primary_key && column.primary
2128 include_readonly_attributes ? quoted : remove_readonly_attributes(quoted)
2131 # Quote strings appropriately for SQL statements.
2132 def quote_value(value, column = nil)
2133 self.class.connection.quote(value, column)
2136 # Interpolate custom sql string in instance context.
2137 # Optional record argument is meant for custom insert_sql.
2138 def interpolate_sql(sql, record = nil)
2139 instance_eval("%@#{sql.gsub('@', '\@')}@")
2142 # Initializes the attributes array with keys matching the columns from the linked table and
2143 # the values matching the corresponding default value of that column, so
2144 # that a new instance, or one populated from a passed-in Hash, still has all the attributes
2145 # that instances loaded from the database would.
2146 def attributes_from_column_definition
2147 self.class.columns.inject({}) do |attributes, column|
2148 attributes[column.name] = column.default unless column.name == self.class.primary_key
2153 # Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done
2154 # by calling new on the column type or aggregation type (through composed_of) object with these parameters.
2155 # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
2156 # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
2157 # parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, f for Float,
2158 # s for String, and a for Array. If all the values for a given attribute are empty, the attribute will be set to nil.
2159 def assign_multiparameter_attributes(pairs)
2160 execute_callstack_for_multiparameter_attributes(
2161 extract_callstack_for_multiparameter_attributes(pairs)
2165 # Includes an ugly hack for Time.local instead of Time.new because the latter is reserved by Time itself.
2166 def execute_callstack_for_multiparameter_attributes(callstack)
2168 callstack.each do |name, values|
2169 klass = (self.class.reflect_on_aggregation(name.to_sym) || column_for_attribute(name)).klass
2171 send(name + "=", nil)
2174 send(name + "=", Time == klass ? (@@default_timezone == :utc ? klass.utc(*values) : klass.local(*values)) : klass.new(*values))
2176 errors << AttributeAssignmentError.new("error on assignment #{values.inspect} to #{name}", ex, name)
2180 unless errors.empty?
2181 raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes"
2185 def extract_callstack_for_multiparameter_attributes(pairs)
2189 multiparameter_name, value = pair
2190 attribute_name = multiparameter_name.split("(").first
2191 attributes[attribute_name] = [] unless attributes.include?(attribute_name)
2194 attributes[attribute_name] <<
2195 [ find_parameter_position(multiparameter_name), type_cast_attribute_value(multiparameter_name, value) ]
2199 attributes.each { |name, values| attributes[name] = values.sort_by{ |v| v.first }.collect { |v| v.last } }
2202 def type_cast_attribute_value(multiparameter_name, value)
2203 multiparameter_name =~ /\([0-9]*([a-z])\)/ ? value.send("to_" + $1) : value
2206 def find_parameter_position(multiparameter_name)
2207 multiparameter_name.scan(/\(([0-9]*).*\)/).first.first
2210 # Returns a comma-separated pair list, like "key1 = val1, key2 = val2".
2211 def comma_pair_list(hash)
2212 hash.inject([]) { |list, pair| list << "#{pair.first} = #{pair.last}" }.join(", ")
2215 def quoted_column_names(attributes = attributes_with_quotes)
2216 attributes.keys.collect do |column_name|
2217 self.class.connection.quote_column_name(column_name)
2221 def self.quoted_table_name
2222 self.connection.quote_table_name(self.table_name)
2225 def quote_columns(quoter, hash)
2226 hash.inject({}) do |quoted, (name, value)|
2227 quoted[quoter.quote_column_name(name)] = value
2232 def quoted_comma_pair_list(quoter, hash)
2233 comma_pair_list(quote_columns(quoter, hash))
2236 def object_from_yaml(string)
2237 return string unless string.is_a?(String)
2238 YAML::load(string) rescue string
2241 def clone_attributes(reader_method = :read_attribute, attributes = {})
2242 self.attribute_names.inject(attributes) do |attributes, name|
2243 attributes[name] = clone_attribute_value(reader_method, name)
2248 def clone_attribute_value(reader_method, attribute_name)
2249 value = send(reader_method, attribute_name)
2250 value.duplicable? ? value.clone : value
2251 rescue TypeError, NoMethodError