1 require 'yaml'
2 require 'set'
3 require 'active_support/benchmarkable'
4 require 'active_support/dependencies'
5 require 'active_support/time'
6 require 'active_support/core_ext/class/attribute_accessors'
7 require 'active_support/core_ext/class/delegating_attributes'
8 require 'active_support/core_ext/class/inheritable_attributes'
9 require 'active_support/core_ext/array/extract_options'
10 require 'active_support/core_ext/hash/deep_merge'
11 require 'active_support/core_ext/hash/indifferent_access'
12 require 'active_support/core_ext/hash/slice'
13 require 'active_support/core_ext/string/behavior'
14 require 'active_support/core_ext/object/metaclass'
15 require 'active_support/core_ext/module/delegation'
16
17 module ActiveRecord #:nodoc:
18 # Generic Active Record exception class.
19 class ActiveRecordError < StandardError
20 end
21
22 # Raised when the single-table inheritance mechanism fails to locate the subclass
23 # (for example due to improper usage of column that +inheritance_column+ points to).
24 class SubclassNotFound < ActiveRecordError #:nodoc:
25 end
26
27 # Raised when an object assigned to an association has an incorrect type.
28 #
29 # class Ticket < ActiveRecord::Base
30 # has_many :patches
31 # end
32 #
33 # class Patch < ActiveRecord::Base
34 # belongs_to :ticket
35 # end
36 #
37 # # Comments are not patches, this assignment raises AssociationTypeMismatch.
38 # @ticket.patches << Comment.new(:content => "Please attach tests to your patch.")
39 class AssociationTypeMismatch < ActiveRecordError
40 end
41
42 # Raised when unserialized object's type mismatches one specified for serializable field.
43 class SerializationTypeMismatch < ActiveRecordError
44 end
45
46 # Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt> misses adapter field).
47 class AdapterNotSpecified < ActiveRecordError
48 end
49
50 # Raised when Active Record cannot find database adapter specified in <tt>config/database.yml</tt> or programmatically.
51 class AdapterNotFound < ActiveRecordError
52 end
53
54 # Raised when connection to the database could not been established (for example when <tt>connection=</tt> is given a nil object).
55 class ConnectionNotEstablished < ActiveRecordError
56 end
57
58 # Raised when Active Record cannot find record by given id or set of ids.
59 class RecordNotFound < ActiveRecordError
60 end
61
62 # Raised by ActiveRecord::Base.save! and ActiveRecord::Base.create! methods when record cannot be
63 # saved because record is invalid.
64 class RecordNotSaved < ActiveRecordError
65 end
66
67 # 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).
68 class StatementInvalid < ActiveRecordError
69 end
70
71 # Raised when SQL statement is invalid and the application gets a blank result.
72 class ThrowResult < ActiveRecordError
73 end
74
75 # Parent class for all specific exceptions which wrap database driver exceptions
76 # provides access to the original exception also.
77 class WrappedDatabaseException < StatementInvalid
78 attr_reader :original_exception
79
80 def initialize(message, original_exception)
81 super(message)
82 @original_exception = original_exception
83 end
84 end
85
86 # Raised when a record cannot be inserted because it would violate a uniqueness constraint.
87 class RecordNotUnique < WrappedDatabaseException
88 end
89
90 # Raised when a record cannot be inserted or updated because it references a non-existent record.
91 class InvalidForeignKey < WrappedDatabaseException
92 end
93
94 # Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example, when using +find+ method)
95 # does not match number of expected variables.
96 #
97 # For example, in
98 #
99 # Location.find :all, :conditions => ["lat = ? AND lng = ?", 53.7362]
100 #
101 # two placeholders are given but only one variable to fill them.
102 class PreparedStatementInvalid < ActiveRecordError
103 end
104
105 # Raised on attempt to save stale record. Record is stale when it's being saved in another query after
106 # instantiation, for example, when two users edit the same wiki page and one starts editing and saves
107 # the page before the other.
108 #
109 # Read more about optimistic locking in ActiveRecord::Locking module RDoc.
110 class StaleObjectError < ActiveRecordError
111 end
112
113 # Raised when association is being configured improperly or
114 # user tries to use offset and limit together with has_many or has_and_belongs_to_many associations.
115 class ConfigurationError < ActiveRecordError
116 end
117
118 # Raised on attempt to update record that is instantiated as read only.
119 class ReadOnlyRecord < ActiveRecordError
120 end
121
122 # ActiveRecord::Transactions::ClassMethods.transaction uses this exception
123 # to distinguish a deliberate rollback from other exceptional situations.
124 # Normally, raising an exception will cause the +transaction+ method to rollback
125 # the database transaction *and* pass on the exception. But if you raise an
126 # ActiveRecord::Rollback exception, then the database transaction will be rolled back,
127 # without passing on the exception.
128 #
129 # For example, you could do this in your controller to rollback a transaction:
130 #
131 # class BooksController < ActionController::Base
132 # def create
133 # Book.transaction do
134 # book = Book.new(params[:book])
135 # book.save!
136 # if today_is_friday?
137 # # The system must fail on Friday so that our support department
138 # # won't be out of job. We silently rollback this transaction
139 # # without telling the user.
140 # raise ActiveRecord::Rollback, "Call tech support!"
141 # end
142 # end
143 # # ActiveRecord::Rollback is the only exception that won't be passed on
144 # # by ActiveRecord::Base.transaction, so this line will still be reached
145 # # even on Friday.
146 # redirect_to root_url
147 # end
148 # end
149 class Rollback < ActiveRecordError
150 end
151
152 # Raised when attribute has a name reserved by Active Record (when attribute has name of one of Active Record instance methods).
153 class DangerousAttributeError < ActiveRecordError
154 end
155
156 # Raised when unknown attributes are supplied via mass assignment.
157 class UnknownAttributeError < NoMethodError
158 end
159
160 # Raised when an error occurred while doing a mass assignment to an attribute through the
161 # <tt>attributes=</tt> method. The exception has an +attribute+ property that is the name of the
162 # offending attribute.
163 class AttributeAssignmentError < ActiveRecordError
164 attr_reader :exception, :attribute
165 def initialize(message, exception, attribute)
166 @exception = exception
167 @attribute = attribute
168 @message = message
169 end
170 end
171
172 # Raised when there are multiple errors while doing a mass assignment through the +attributes+
173 # method. The exception has an +errors+ property that contains an array of AttributeAssignmentError
174 # objects, each corresponding to the error while assigning to an attribute.
175 class MultiparameterAssignmentErrors < ActiveRecordError
176 attr_reader :errors
177 def initialize(errors)
178 @errors = errors
179 end
180 end
181
182 # Active Record objects don't specify their attributes directly, but rather infer them from the table definition with
183 # which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change
184 # is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain
185 # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
186 #
187 # See the mapping rules in table_name and the full example in link:files/README.html for more insight.
188 #
189 # == Creation
190 #
191 # Active Records accept constructor parameters either in a hash or as a block. The hash method is especially useful when
192 # you're receiving the data from somewhere else, like an HTTP request. It works like this:
193 #
194 # user = User.new(:name => "David", :occupation => "Code Artist")
195 # user.name # => "David"
196 #
197 # You can also use block initialization:
198 #
199 # user = User.new do |u|
200 # u.name = "David"
201 # u.occupation = "Code Artist"
202 # end
203 #
204 # And of course you can just create a bare object and specify the attributes after the fact:
205 #
206 # user = User.new
207 # user.name = "David"
208 # user.occupation = "Code Artist"
209 #
210 # == Conditions
211 #
212 # Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement.
213 # The array form is to be used when the condition input is tainted and requires sanitization. The string form can
214 # be used for statements that don't involve tainted data. The hash form works much like the array form, except
215 # only equality and range is possible. Examples:
216 #
217 # class User < ActiveRecord::Base
218 # def self.authenticate_unsafely(user_name, password)
219 # find(:first, :conditions => "user_name = '#{user_name}' AND password = '#{password}'")
220 # end
221 #
222 # def self.authenticate_safely(user_name, password)
223 # find(:first, :conditions => [ "user_name = ? AND password = ?", user_name, password ])
224 # end
225 #
226 # def self.authenticate_safely_simply(user_name, password)
227 # find(:first, :conditions => { :user_name => user_name, :password => password })
228 # end
229 # end
230 #
231 # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection
232 # attacks if the <tt>user_name</tt> and +password+ parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and
233 # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+ before inserting them in the query,
234 # which will ensure that an attacker can't escape the query and fake the login (or worse).
235 #
236 # When using multiple parameters in the conditions, it can easily become hard to read exactly what the fourth or fifth
237 # question mark is supposed to represent. In those cases, you can resort to named bind variables instead. That's done by replacing
238 # the question marks with symbols and supplying a hash with values for the matching symbol keys:
239 #
240 # Company.find(:first, :conditions => [
241 # "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
242 # { :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' }
243 # ])
244 #
245 # Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
246 # operator. For instance:
247 #
248 # Student.find(:all, :conditions => { :first_name => "Harvey", :status => 1 })
249 # Student.find(:all, :conditions => params[:student])
250 #
251 # A range may be used in the hash to use the SQL BETWEEN operator:
252 #
253 # Student.find(:all, :conditions => { :grade => 9..12 })
254 #
255 # An array may be used in the hash to use the SQL IN operator:
256 #
257 # Student.find(:all, :conditions => { :grade => [9,11,12] })
258 #
259 # When joining tables, nested hashes or keys written in the form 'table_name.column_name' can be used to qualify the table name of a
260 # particular condition. For instance:
261 #
262 # Student.find(:all, :conditions => { :schools => { :type => 'public' }}, :joins => :schools)
263 # Student.find(:all, :conditions => { 'schools.type' => 'public' }, :joins => :schools)
264 #
265 # == Overwriting default accessors
266 #
267 # All column values are automatically available through basic accessors on the Active Record object, but sometimes you
268 # want to specialize this behavior. This can be done by overwriting the default accessors (using the same
269 # name as the attribute) and calling <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually change things.
270 # Example:
271 #
272 # class Song < ActiveRecord::Base
273 # # Uses an integer of seconds to hold the length of the song
274 #
275 # def length=(minutes)
276 # write_attribute(:length, minutes.to_i * 60)
277 # end
278 #
279 # def length
280 # read_attribute(:length) / 60
281 # end
282 # end
283 #
284 # You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt> instead of <tt>write_attribute(:attribute, value)</tt> and
285 # <tt>read_attribute(:attribute)</tt> as a shorter form.
286 #
287 # == Attribute query methods
288 #
289 # In addition to the basic accessors, query methods are also automatically available on the Active Record object.
290 # Query methods allow you to test whether an attribute value is present.
291 #
292 # For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
293 # to determine whether the user has a name:
294 #
295 # user = User.new(:name => "David")
296 # user.name? # => true
297 #
298 # anonymous = User.new(:name => "")
299 # anonymous.name? # => false
300 #
301 # == Accessing attributes before they have been typecasted
302 #
303 # Sometimes you want to be able to read the raw attribute data without having the column-determined typecast run its course first.
304 # That can be done by using the <tt><attribute>_before_type_cast</tt> accessors that all attributes have. For example, if your Account model
305 # has a <tt>balance</tt> attribute, you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>.
306 #
307 # This is especially useful in validation situations where the user might supply a string for an integer field and you want to display
308 # the original string back in an error message. Accessing the attribute normally would typecast the string to 0, which isn't what you
309 # want.
310 #
311 # == Dynamic attribute-based finders
312 #
313 # Dynamic attribute-based finders are a cleaner way of getting (and/or creating) objects by simple queries without turning to SQL. They work by
314 # 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>,
315 # <tt>Person.find_all_by_last_name</tt>, and <tt>Payment.find_by_transaction_id</tt>. So instead of writing
316 # <tt>Person.find(:first, :conditions => ["user_name = ?", user_name])</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
317 # 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>.
318 #
319 # It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like
320 # <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
321 # <tt>Person.find(:first, :conditions => ["user_name = ? AND password = ?", user_name, password])</tt>, you just do
322 # <tt>Person.find_by_user_name_and_password(user_name, password)</tt>.
323 #
324 # 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>
325 # is actually <tt>Payment.find_all_by_amount(amount, options)</tt>. And the full interface to <tt>Person.find_by_user_name</tt> is
326 # 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>.
327 # Also you may call <tt>Payment.find_last_by_amount(amount, options)</tt> returning the last record matching that amount and options.
328 #
329 # The same dynamic finder style can be used to create the object if it doesn't already exist. This dynamic finder is called with
330 # <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:
331 #
332 # # No 'Summer' tag exists
333 # Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
334 #
335 # # Now the 'Summer' tag does exist
336 # Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
337 #
338 # # Now 'Bob' exist and is an 'admin'
339 # User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }
340 #
341 # 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:
342 #
343 # # No 'Winter' tag exists
344 # winter = Tag.find_or_initialize_by_name("Winter")
345 # winter.new_record? # true
346 #
347 # To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of
348 # a list of parameters. For example:
349 #
350 # Tag.find_or_create_by_name(:name => "rails", :creator => current_user)
351 #
352 # That will either find an existing tag named "rails", or create a new one while setting the user that created it.
353 #
354 # == Saving arrays, hashes, and other non-mappable objects in text columns
355 #
356 # 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+.
357 # This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work. Example:
358 #
359 # class User < ActiveRecord::Base
360 # serialize :preferences
361 # end
362 #
363 # user = User.create(:preferences => { "background" => "black", "display" => large })
364 # User.find(user.id).preferences # => { "background" => "black", "display" => large }
365 #
366 # You can also specify a class option as the second parameter that'll raise an exception if a serialized object is retrieved as a
367 # descendant of a class not in the hierarchy. Example:
368 #
369 # class User < ActiveRecord::Base
370 # serialize :preferences, Hash
371 # end
372 #
373 # user = User.create(:preferences => %w( one two three ))
374 # User.find(user.id).preferences # raises SerializationTypeMismatch
375 #
376 # == Single table inheritance
377 #
378 # Active Record allows inheritance by storing the name of the class in a column that by default is named "type" (can be changed
379 # by overwriting <tt>Base.inheritance_column</tt>). This means that an inheritance looking like this:
380 #
381 # class Company < ActiveRecord::Base; end
382 # class Firm < Company; end
383 # class Client < Company; end
384 # class PriorityClient < Client; end
385 #
386 # When you do <tt>Firm.create(:name => "37signals")</tt>, this record will be saved in the companies table with type = "Firm". You can then
387 # fetch this row again using <tt>Company.find(:first, "name = '37signals'")</tt> and it will return a Firm object.
388 #
389 # 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
390 # like normal subclasses with no special magic for differentiating between them or reloading the right type with find.
391 #
392 # Note, all the attributes for all the cases are kept in the same table. Read more:
393 # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
394 #
395 # == Connection to multiple databases in different models
396 #
397 # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection.
398 # All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection.
399 # For example, if Course is an ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
400 # and Course and all of its subclasses will use this connection instead.
401 #
402 # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is
403 # requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool.
404 #
405 # == Exceptions
406 #
407 # * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record.
408 # * AdapterNotSpecified - The configuration hash used in <tt>establish_connection</tt> didn't include an
409 # <tt>:adapter</tt> key.
410 # * AdapterNotFound - The <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a non-existent adapter
411 # (or a bad spelling of an existing one).
412 # * AssociationTypeMismatch - The object assigned to the association wasn't of the type specified in the association definition.
413 # * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
414 # * ConnectionNotEstablished+ - No connection has been established. Use <tt>establish_connection</tt> before querying.
415 # * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
416 # or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
417 # nothing was found, please check its documentation for further details.
418 # * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
419 # * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the
420 # <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of AttributeAssignmentError
421 # objects that should be inspected to determine which attributes triggered the errors.
422 # * AttributeAssignmentError - An error occurred while doing a mass assignment through the <tt>attributes=</tt> method.
423 # You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error.
424 #
425 # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
426 # So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all
427 # instances in the current object space.
428 class Base
429 ##
430 # :singleton-method:
431 # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed
432 # on to any new database connections made and which can be retrieved on both a class and instance level by calling +logger+.
433 cattr_accessor :logger, :instance_writer => false
434
435 def self.inherited(child) #:nodoc:
436 @@subclasses[self] ||= []
437 @@subclasses[self] << child
438 super
439 end
440
441 def self.reset_subclasses #:nodoc:
442 nonreloadables = []
443 subclasses.each do |klass|
444 unless ActiveSupport::Dependencies.autoloaded? klass
445 nonreloadables << klass
446 next
447 end
448 klass.instance_variables.each { |var| klass.send(:remove_instance_variable, var) }
449 klass.instance_methods(false).each { |m| klass.send :undef_method, m }
450 end
451 @@subclasses = {}
452 nonreloadables.each { |klass| (@@subclasses[klass.superclass] ||= []) << klass }
453 end
454
455 @@subclasses = {}
456
457 ##
458 # :singleton-method:
459 # Contains the database configuration - as is typically stored in config/database.yml -
460 # as a Hash.
461 #
462 # For example, the following database.yml...
463 #
464 # development:
465 # adapter: sqlite3
466 # database: db/development.sqlite3
467 #
468 # production:
469 # adapter: sqlite3
470 # database: db/production.sqlite3
471 #
472 # ...would result in ActiveRecord::Base.configurations to look like this:
473 #
474 # {
475 # 'development' => {
476 # 'adapter' => 'sqlite3',
477 # 'database' => 'db/development.sqlite3'
478 # },
479 # 'production' => {
480 # 'adapter' => 'sqlite3',
481 # 'database' => 'db/production.sqlite3'
482 # }
483 # }
484 cattr_accessor :configurations, :instance_writer => false
485 @@configurations = {}
486
487 ##
488 # :singleton-method:
489 # Accessor for the prefix type that will be prepended to every primary key column name. The options are :table_name and
490 # :table_name_with_underscore. If the first is specified, the Product class will look for "productid" instead of "id" as
491 # the primary column. If the latter is specified, the Product class will look for "product_id" instead of "id". Remember
492 # that this is a global setting for all Active Records.
493 cattr_accessor :primary_key_prefix_type, :instance_writer => false
494 @@primary_key_prefix_type = nil
495
496 ##
497 # :singleton-method:
498 # Accessor for the name of the prefix string to prepend to every table name. So if set to "basecamp_", all
499 # table names will be named like "basecamp_projects", "basecamp_people", etc. This is a convenient way of creating a namespace
500 # for tables in a shared database. By default, the prefix is the empty string.
501 cattr_accessor :table_name_prefix, :instance_writer => false
502 @@table_name_prefix = ""
503
504 ##
505 # :singleton-method:
506 # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
507 # "people_basecamp"). By default, the suffix is the empty string.
508 cattr_accessor :table_name_suffix, :instance_writer => false
509 @@table_name_suffix = ""
510
511 ##
512 # :singleton-method:
513 # Indicates whether table names should be the pluralized versions of the corresponding class names.
514 # If true, the default table name for a Product class will be +products+. If false, it would just be +product+.
515 # See table_name for the full rules on table/class naming. This is true, by default.
516 cattr_accessor :pluralize_table_names, :instance_writer => false
517 @@pluralize_table_names = true
518
519 ##
520 # :singleton-method:
521 # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates and times from the database.
522 # This is set to :local by default.
523 cattr_accessor :default_timezone, :instance_writer => false
524 @@default_timezone = :local
525
526 ##
527 # :singleton-method:
528 # Specifies the format to use when dumping the database schema with Rails'
529 # Rakefile. If :sql, the schema is dumped as (potentially database-
530 # specific) SQL statements. If :ruby, the schema is dumped as an
531 # ActiveRecord::Schema file which can be loaded into any database that
532 # supports migrations. Use :ruby if you want to have different database
533 # adapters for, e.g., your development and test environments.
534 cattr_accessor :schema_format , :instance_writer => false
535 @@schema_format = :ruby
536
537 ##
538 # :singleton-method:
539 # Specify whether or not to use timestamps for migration numbers
540 cattr_accessor :timestamped_migrations , :instance_writer => false
541 @@timestamped_migrations = true
542
543 # Determine whether to store the full constant name including namespace when using STI
544 superclass_delegating_accessor :store_full_sti_class
545 self.store_full_sti_class = true
546
547 # Stores the default scope for the class
548 class_inheritable_accessor :default_scoping, :instance_writer => false
549 self.default_scoping = []
550
551 class << self # Class methods
552 def colorize_logging(*args)
553 ActiveSupport::Deprecation.warn "ActiveRecord::Base.colorize_logging and " <<
554 "config.active_record.colorize_logging are deprecated. Please use " <<
555 "Rails::Subscriber.colorize_logging or config.colorize_logging instead", caller
556 end
557 alias :colorize_logging= :colorize_logging
558
559 delegate :find, :first, :last, :all, :destroy, :destroy_all, :exists?, :delete, :delete_all, :update, :update_all, :to => :scoped
560 delegate :select, :group, :order, :limit, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :to => :scoped
561 delegate :count, :average, :minimum, :maximum, :sum, :calculate, :to => :scoped
562
563 # Executes a custom SQL query against your database and returns all the results. The results will
564 # be returned as an array with columns requested encapsulated as attributes of the model you call
565 # this method from. If you call <tt>Product.find_by_sql</tt> then the results will be returned in
566 # a Product object with the attributes you specified in the SQL query.
567 #
568 # If you call a complicated SQL query which spans multiple tables the columns specified by the
569 # SELECT will be attributes of the model, whether or not they are columns of the corresponding
570 # table.
571 #
572 # The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be
573 # no database agnostic conversions performed. This should be a last resort because using, for example,
574 # MySQL specific terms will lock you to using that particular database engine or require you to
575 # change your call if you switch engines.
576 #
577 # ==== Examples
578 # # A simple SQL query spanning multiple tables
579 # Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
580 # > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
581 #
582 # # You can use the same string replacement techniques as you can with ActiveRecord#find
583 # Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
584 # > [#<Post:0x36bff9c @attributes={"first_name"=>"The Cheap Man Buys Twice"}>, ...]
585 def find_by_sql(sql)
586 connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) }
587 end
588
589 # Creates an object (or multiple objects) and saves it to the database, if validations pass.
590 # The resulting object is returned whether the object was saved successfully to the database or not.
591 #
592 # The +attributes+ parameter can be either be a Hash or an Array of Hashes. These Hashes describe the
593 # attributes on the objects that are to be created.
594 #
595 # ==== Examples
596 # # Create a single new object
597 # User.create(:first_name => 'Jamie')
598 #
599 # # Create an Array of new objects
600 # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])
601 #
602 # # Create a single object and pass it into a block to set other attributes.
603 # User.create(:first_name => 'Jamie') do |u|
604 # u.is_admin = false
605 # end
606 #
607 # # Creating an Array of new objects using a block, where the block is executed for each object:
608 # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u|
609 # u.is_admin = false
610 # end
611 def create(attributes = nil, &block)
612 if attributes.is_a?(Array)
613 attributes.collect { |attr| create(attr, &block) }
614 else
615 object = new(attributes)
616 yield(object) if block_given?
617 object.save
618 object
619 end
620 end
621
622 # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
623 # The use of this method should be restricted to complicated SQL queries that can't be executed
624 # using the ActiveRecord::Calculations class methods. Look into those before using this.
625 #
626 # ==== Parameters
627 #
628 # * +sql+ - An SQL statement which should return a count query from the database, see the example below.
629 #
630 # ==== Examples
631 #
632 # Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
633 def count_by_sql(sql)
634 sql = sanitize_conditions(sql)
635 connection.select_value(sql, "#{name} Count").to_i
636 end
637
638 # Resets one or more counter caches to their correct value using an SQL
639 # count query. This is useful when adding new counter caches, or if the
640 # counter has been corrupted or modified directly by SQL.
641 #
642 # ==== Parameters
643 #
644 # * +id+ - The id of the object you wish to reset a counter on.
645 # * +counters+ - One or more counter names to reset
646 #
647 # ==== Examples
648 #
649 # # For Post with id #1 records reset the comments_count
650 # Post.reset_counters(1, :comments)
651 def reset_counters(id, *counters)
652 object = find(id)
653 counters.each do |association|
654 child_class = reflect_on_association(association).klass
655 counter_name = child_class.reflect_on_association(self.name.downcase.to_sym).counter_cache_column
656
657 connection.update("UPDATE #{quoted_table_name} SET #{connection.quote_column_name(counter_name)} = #{object.send(association).count} WHERE #{connection.quote_column_name(primary_key)} = #{quote_value(object.id)}", "#{name} UPDATE")
658 end
659 end
660
661 # A generic "counter updater" implementation, intended primarily to be
662 # used by increment_counter and decrement_counter, but which may also
663 # be useful on its own. It simply does a direct SQL update for the record
664 # with the given ID, altering the given hash of counters by the amount
665 # given by the corresponding value:
666 #
667 # ==== Parameters
668 #
669 # * +id+ - The id of the object you wish to update a counter on or an Array of ids.
670 # * +counters+ - An Array of Hashes containing the names of the fields
671 # to update as keys and the amount to update the field by as values.
672 #
673 # ==== Examples
674 #
675 # # For the Post with id of 5, decrement the comment_count by 1, and
676 # # increment the action_count by 1
677 # Post.update_counters 5, :comment_count => -1, :action_count => 1
678 # # Executes the following SQL:
679 # # UPDATE posts
680 # # SET comment_count = comment_count - 1,
681 # # action_count = action_count + 1
682 # # WHERE id = 5
683 #
684 # # For the Posts with id of 10 and 15, increment the comment_count by 1
685 # Post.update_counters [10, 15], :comment_count => 1
686 # # Executes the following SQL:
687 # # UPDATE posts
688 # # SET comment_count = comment_count + 1,
689 # # WHERE id IN (10, 15)
690 def update_counters(id, counters)
691 updates = counters.inject([]) { |list, (counter_name, increment)|
692 sign = increment < 0 ? "-" : "+"
693 list << "#{connection.quote_column_name(counter_name)} = COALESCE(#{connection.quote_column_name(counter_name)}, 0) #{sign} #{increment.abs}"
694 }.join(", ")
695
696 if id.is_a?(Array)
697 ids_list = id.map {|i| quote_value(i)}.join(', ')
698 condition = "IN (#{ids_list})"
699 else
700 condition = "= #{quote_value(id)}"
701 end
702
703 update_all(updates, "#{connection.quote_column_name(primary_key)} #{condition}")
704 end
705
706 # Increment a number field by one, usually representing a count.
707 #
708 # This is used for caching aggregate values, so that they don't need to be computed every time.
709 # For example, a DiscussionBoard may cache post_count and comment_count otherwise every time the board is
710 # shown it would have to run an SQL query to find how many posts and comments there are.
711 #
712 # ==== Parameters
713 #
714 # * +counter_name+ - The name of the field that should be incremented.
715 # * +id+ - The id of the object that should be incremented.
716 #
717 # ==== Examples
718 #
719 # # Increment the post_count column for the record with an id of 5
720 # DiscussionBoard.increment_counter(:post_count, 5)
721 def increment_counter(counter_name, id)
722 update_counters(id, counter_name => 1)
723 end
724
725 # Decrement a number field by one, usually representing a count.
726 #
727 # This works the same as increment_counter but reduces the column value by 1 instead of increasing it.
728 #
729 # ==== Parameters
730 #
731 # * +counter_name+ - The name of the field that should be decremented.
732 # * +id+ - The id of the object that should be decremented.
733 #
734 # ==== Examples
735 #
736 # # Decrement the post_count column for the record with an id of 5
737 # DiscussionBoard.decrement_counter(:post_count, 5)
738 def decrement_counter(counter_name, id)
739 update_counters(id, counter_name => -1)
740 end
741
742 # Attributes named in this macro are protected from mass-assignment,
743 # such as <tt>new(attributes)</tt>,
744 # <tt>update_attributes(attributes)</tt>, or
745 # <tt>attributes=(attributes)</tt>.
746 #
747 # Mass-assignment to these attributes will simply be ignored, to assign
748 # to them you can use direct writer methods. This is meant to protect
749 # sensitive attributes from being overwritten by malicious users
750 # tampering with URLs or forms.
751 #
752 # class Customer < ActiveRecord::Base
753 # attr_protected :credit_rating
754 # end
755 #
756 # customer = Customer.new("name" => David, "credit_rating" => "Excellent")
757 # customer.credit_rating # => nil
758 # customer.attributes = { "description" => "Jolly fellow", "credit_rating" => "Superb" }
759 # customer.credit_rating # => nil
760 #
761 # customer.credit_rating = "Average"
762 # customer.credit_rating # => "Average"
763 #
764 # To start from an all-closed default and enable attributes as needed,
765 # have a look at +attr_accessible+.
766 #
767 # If the access logic of your application is richer you can use <tt>Hash#except</tt>
768 # or <tt>Hash#slice</tt> to sanitize the hash of parameters before they are
769 # passed to Active Record.
770 #
771 # For example, it could be the case that the list of protected attributes
772 # for a given model depends on the role of the user:
773 #
774 # # Assumes plan_id is not protected because it depends on the role.
775 # params[:account] = params[:account].except(:plan_id) unless admin?
776 # @account.update_attributes(params[:account])
777 #
778 # Note that +attr_protected+ is still applied to the received hash. Thus,
779 # with this technique you can at most _extend_ the list of protected
780 # attributes for a particular mass-assignment call.
781 def attr_protected(*attributes)
782 write_inheritable_attribute(:attr_protected, Set.new(attributes.map {|a| a.to_s}) + (protected_attributes || []))
783 end
784
785 # Returns an array of all the attributes that have been protected from mass-assignment.
786 def protected_attributes # :nodoc:
787 read_inheritable_attribute(:attr_protected)
788 end
789
790 # Specifies a white list of model attributes that can be set via
791 # mass-assignment, such as <tt>new(attributes)</tt>,
792 # <tt>update_attributes(attributes)</tt>, or
793 # <tt>attributes=(attributes)</tt>
794 #
795 # This is the opposite of the +attr_protected+ macro: Mass-assignment
796 # will only set attributes in this list, to assign to the rest of
797 # attributes you can use direct writer methods. This is meant to protect
798 # sensitive attributes from being overwritten by malicious users
799 # tampering with URLs or forms. If you'd rather start from an all-open
800 # default and restrict attributes as needed, have a look at
801 # +attr_protected+.
802 #
803 # class Customer < ActiveRecord::Base
804 # attr_accessible :name, :nickname
805 # end
806 #
807 # customer = Customer.new(:name => "David", :nickname => "Dave", :credit_rating => "Excellent")
808 # customer.credit_rating # => nil
809 # customer.attributes = { :name => "Jolly fellow", :credit_rating => "Superb" }
810 # customer.credit_rating # => nil
811 #
812 # customer.credit_rating = "Average"
813 # customer.credit_rating # => "Average"
814 #
815 # If the access logic of your application is richer you can use <tt>Hash#except</tt>
816 # or <tt>Hash#slice</tt> to sanitize the hash of parameters before they are
817 # passed to Active Record.
818 #
819 # For example, it could be the case that the list of accessible attributes
820 # for a given model depends on the role of the user:
821 #
822 # # Assumes plan_id is accessible because it depends on the role.
823 # params[:account] = params[:account].except(:plan_id) unless admin?
824 # @account.update_attributes(params[:account])
825 #
826 # Note that +attr_accessible+ is still applied to the received hash. Thus,
827 # with this technique you can at most _narrow_ the list of accessible
828 # attributes for a particular mass-assignment call.
829 def attr_accessible(*attributes)
830 write_inheritable_attribute(:attr_accessible, Set.new(attributes.map(&:to_s)) + (accessible_attributes || []))
831 end
832
833 # Returns an array of all the attributes that have been made accessible to mass-assignment.
834 def accessible_attributes # :nodoc:
835 read_inheritable_attribute(:attr_accessible)
836 end
837
838 # Attributes listed as readonly can be set for a new record, but will be ignored in database updates afterwards.
839 def attr_readonly(*attributes)
840 write_inheritable_attribute(:attr_readonly, Set.new(attributes.map(&:to_s)) + (readonly_attributes || []))
841 end
842
843 # Returns an array of all the attributes that have been specified as readonly.
844 def readonly_attributes
845 read_inheritable_attribute(:attr_readonly) || []
846 end
847
848 # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object,
849 # then specify the name of that attribute using this method and it will be handled automatically.
850 # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that
851 # class on retrieval or SerializationTypeMismatch will be raised.
852 #
853 # ==== Parameters
854 #
855 # * +attr_name+ - The field name that should be serialized.
856 # * +class_name+ - Optional, class name that the object type should be equal to.
857 #
858 # ==== Example
859 # # Serialize a preferences attribute
860 # class User
861 # serialize :preferences
862 # end
863 def serialize(attr_name, class_name = Object)
864 serialized_attributes[attr_name.to_s] = class_name
865 end
866
867 # Returns a hash of all the attributes that have been specified for serialization as keys and their class restriction as values.
868 def serialized_attributes
869 read_inheritable_attribute(:attr_serialized) or write_inheritable_attribute(:attr_serialized, {})
870 end
871
872 # Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending
873 # directly from ActiveRecord::Base. So if the hierarchy looks like: Reply < Message < ActiveRecord::Base, then Message is used
874 # to guess the table name even when called on Reply. The rules used to do the guess are handled by the Inflector class
875 # in Active Support, which knows almost all common English inflections. You can add new inflections in config/initializers/inflections.rb.
876 #
877 # Nested classes are given table names prefixed by the singular form of
878 # the parent's table name. Enclosing modules are not considered.
879 #
880 # ==== Examples
881 #
882 # class Invoice < ActiveRecord::Base; end;
883 # file class table_name
884 # invoice.rb Invoice invoices
885 #
886 # class Invoice < ActiveRecord::Base; class Lineitem < ActiveRecord::Base; end; end;
887 # file class table_name
888 # invoice.rb Invoice::Lineitem invoice_lineitems
889 #
890 # module Invoice; class Lineitem < ActiveRecord::Base; end; end;
891 # file class table_name
892 # invoice/lineitem.rb Invoice::Lineitem lineitems
893 #
894 # Additionally, the class-level +table_name_prefix+ is prepended and the
895 # +table_name_suffix+ is appended. So if you have "myapp_" as a prefix,
896 # the table name guess for an Invoice class becomes "myapp_invoices".
897 # Invoice::Lineitem becomes "myapp_invoice_lineitems".
898 #
899 # You can also overwrite this class method to allow for unguessable
900 # links, such as a Mouse class with a link to a "mice" table. Example:
901 #
902 # class Mouse < ActiveRecord::Base
903 # set_table_name "mice"
904 # end
905 def table_name
906 reset_table_name
907 end
908
909 def quoted_table_name
910 @quoted_table_name ||= connection.quote_table_name(table_name)
911 end
912
913 def reset_table_name #:nodoc:
914 base = base_class
915
916 name =
917 # STI subclasses always use their superclass' table.
918 unless self == base
919 base.table_name
920 else
921 # Nested classes are prefixed with singular parent table name.
922 if parent < ActiveRecord::Base && !parent.abstract_class?
923 contained = parent.table_name
924 contained = contained.singularize if parent.pluralize_table_names
925 contained << '_'
926 end
927 name = "#{table_name_prefix}#{contained}#{undecorated_table_name(base.name)}#{table_name_suffix}"
928 end
929
930 @quoted_table_name = nil
931 set_table_name(name)
932 name
933 end
934
935 # Defines the column name for use with single table inheritance
936 # -- can be set in subclasses like so: self.inheritance_column = "type_id"
937 def inheritance_column
938 @inheritance_column ||= "type".freeze
939 end
940
941 # Lazy-set the sequence name to the connection's default. This method
942 # is only ever called once since set_sequence_name overrides it.
943 def sequence_name #:nodoc:
944 reset_sequence_name
945 end
946
947 def reset_sequence_name #:nodoc:
948 default = connection.default_sequence_name(table_name, primary_key)
949 set_sequence_name(default)
950 default
951 end
952
953 # Sets the table name to use to the given value, or (if the value
954 # is nil or false) to the value returned by the given block.
955 #
956 # class Project < ActiveRecord::Base
957 # set_table_name "project"
958 # end
959 def set_table_name(value = nil, &block)
960 define_attr_method :table_name, value, &block
961 end
962 alias :table_name= :set_table_name
963
964 # Sets the name of the inheritance column to use to the given value,
965 # or (if the value # is nil or false) to the value returned by the
966 # given block.
967 #
968 # class Project < ActiveRecord::Base
969 # set_inheritance_column do
970 # original_inheritance_column + "_id"
971 # end
972 # end
973 def set_inheritance_column(value = nil, &block)
974 define_attr_method :inheritance_column, value, &block
975 end
976 alias :inheritance_column= :set_inheritance_column
977
978 # Sets the name of the sequence to use when generating ids to the given
979 # value, or (if the value is nil or false) to the value returned by the
980 # given block. This is required for Oracle and is useful for any
981 # database which relies on sequences for primary key generation.
982 #
983 # If a sequence name is not explicitly set when using Oracle or Firebird,
984 # it will default to the commonly used pattern of: #{table_name}_seq
985 #
986 # If a sequence name is not explicitly set when using PostgreSQL, it
987 # will discover the sequence corresponding to your primary key for you.
988 #
989 # class Project < ActiveRecord::Base
990 # set_sequence_name "projectseq" # default would have been "project_seq"
991 # end
992 def set_sequence_name(value = nil, &block)
993 define_attr_method :sequence_name, value, &block
994 end
995 alias :sequence_name= :set_sequence_name
996
997 # Turns the +table_name+ back into a class name following the reverse rules of +table_name+.
998 def class_name(table_name = table_name) # :nodoc:
999 # remove any prefix and/or suffix from the table name
1000 class_name = table_name[table_name_prefix.length..-(table_name_suffix.length + 1)].camelize
1001 class_name = class_name.singularize if pluralize_table_names
1002 class_name
1003 end
1004
1005 # Indicates whether the table associated with this class exists
1006 def table_exists?
1007 connection.table_exists?(table_name)
1008 end
1009
1010 # Returns an array of column objects for the table associated with this class.
1011 def columns
1012 unless defined?(@columns) && @columns
1013 @columns = connection.columns(table_name, "#{name} Columns")
1014 @columns.each { |column| column.primary = column.name == primary_key }
1015 end
1016 @columns
1017 end
1018
1019 # Returns a hash of column objects for the table associated with this class.
1020 def columns_hash
1021 @columns_hash ||= columns.inject({}) { |hash, column| hash[column.name] = column; hash }
1022 end
1023
1024 # Returns an array of column names as strings.
1025 def column_names
1026 @column_names ||= columns.map { |column| column.name }
1027 end
1028
1029 # Returns an array of column objects where the primary id, all columns ending in "_id" or "_count",
1030 # and columns used for single table inheritance have been removed.
1031 def content_columns
1032 @content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column }
1033 end
1034
1035 # 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
1036 # 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
1037 # is available.
1038 def column_methods_hash #:nodoc:
1039 @dynamic_methods_hash ||= column_names.inject(Hash.new(false)) do |methods, attr|
1040 attr_name = attr.to_s
1041 methods[attr.to_sym] = attr_name
1042 methods["#{attr}=".to_sym] = attr_name
1043 methods["#{attr}?".to_sym] = attr_name
1044 methods["#{attr}_before_type_cast".to_sym] = attr_name
1045 methods
1046 end
1047 end
1048
1049 # Resets all the cached information about columns, which will cause them
1050 # to be reloaded on the next request.
1051 #
1052 # The most common usage pattern for this method is probably in a migration,
1053 # when just after creating a table you want to populate it with some default
1054 # values, eg:
1055 #
1056 # class CreateJobLevels < ActiveRecord::Migration
1057 # def self.up
1058 # create_table :job_levels do |t|
1059 # t.integer :id
1060 # t.string :name
1061 #
1062 # t.timestamps
1063 # end
1064 #
1065 # JobLevel.reset_column_information
1066 # %w{assistant executive manager director}.each do |type|
1067 # JobLevel.create(:name => type)
1068 # end
1069 # end
1070 #
1071 # def self.down
1072 # drop_table :job_levels
1073 # end
1074 # end
1075 def reset_column_information
1076 undefine_attribute_methods
1077 @column_names = @columns = @columns_hash = @content_columns = @dynamic_methods_hash = @inheritance_column = nil
1078 @arel_engine = @unscoped = @arel_table = nil
1079 end
1080
1081 def reset_column_information_and_inheritable_attributes_for_all_subclasses#:nodoc:
1082 subclasses.each { |klass| klass.reset_inheritable_attributes; klass.reset_column_information }
1083 end
1084
1085 # Set the lookup ancestors for ActiveModel.
1086 def lookup_ancestors #:nodoc:
1087 klass = self
1088 classes = [klass]
1089 while klass != klass.base_class
1090 classes << klass = klass.superclass
1091 end
1092 classes
1093 rescue
1094 # OPTIMIZE this rescue is to fix this test: ./test/cases/reflection_test.rb:56:in `test_human_name_for_column'
1095 # Apparently the method base_class causes some trouble.
1096 # It now works for sure.
1097 [self]
1098 end
1099
1100 # Set the i18n scope to overwrite ActiveModel.
1101 def i18n_scope #:nodoc:
1102 :activerecord
1103 end
1104
1105 # True if this isn't a concrete subclass needing a STI type condition.
1106 def descends_from_active_record?
1107 if superclass.abstract_class?
1108 superclass.descends_from_active_record?
1109 else
1110 superclass == Base || !columns_hash.include?(inheritance_column)
1111 end
1112 end
1113
1114 def finder_needs_type_condition? #:nodoc:
1115 # This is like this because benchmarking justifies the strange :false stuff
1116 :true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true)
1117 end
1118
1119 # Returns a string like 'Post id:integer, title:string, body:text'
1120 def inspect
1121 if self == Base
1122 super
1123 elsif abstract_class?
1124 "#{super}(abstract)"
1125 elsif table_exists?
1126 attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', '
1127 "#{super}(#{attr_list})"
1128 else
1129 "#{super}(Table doesn't exist)"
1130 end
1131 end
1132
1133 def quote_value(value, column = nil) #:nodoc:
1134 connection.quote(value,column)
1135 end
1136
1137 # Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>.
1138 def sanitize(object) #:nodoc:
1139 connection.quote(object)
1140 end
1141
1142 # Overwrite the default class equality method to provide support for association proxies.
1143 def ===(object)
1144 object.is_a?(self)
1145 end
1146
1147 # Returns the base AR subclass that this class descends from. If A
1148 # extends AR::Base, A.base_class will return A. If B descends from A
1149 # through some arbitrarily deep hierarchy, B.base_class will return A.
1150 def base_class
1151 class_of_active_record_descendant(self)
1152 end
1153
1154 # Set this to true if this is an abstract class (see <tt>abstract_class?</tt>).
1155 attr_accessor :abstract_class
1156
1157 # Returns whether this class is a base AR class. If A is a base class and
1158 # B descends from A, then B.base_class will return B.
1159 def abstract_class?
1160 defined?(@abstract_class) && @abstract_class == true
1161 end
1162
1163 def respond_to?(method_id, include_private = false)
1164 if match = DynamicFinderMatch.match(method_id)
1165 return true if all_attributes_exists?(match.attribute_names)
1166 elsif match = DynamicScopeMatch.match(method_id)
1167 return true if all_attributes_exists?(match.attribute_names)
1168 end
1169
1170 super
1171 end
1172
1173 def sti_name
1174 store_full_sti_class ? name : name.demodulize
1175 end
1176
1177 def unscoped
1178 @unscoped ||= Relation.new(self, arel_table)
1179 finder_needs_type_condition? ? @unscoped.where(type_condition) : @unscoped
1180 end
1181
1182 def arel_table
1183 @arel_table ||= Arel::Table.new(table_name, :engine => arel_engine)
1184 end
1185
1186 def arel_engine
1187 @arel_engine ||= begin
1188 if self == ActiveRecord::Base
1189 Arel::Table.engine
1190 else
1191 connection_handler.connection_pools[name] ? Arel::Sql::Engine.new(self) : superclass.arel_engine
1192 end
1193 end
1194 end
1195
1196 private
1197 # Finder methods must instantiate through this method to work with the
1198 # single-table inheritance model that makes it possible to create
1199 # objects of different types from the same table.
1200 def instantiate(record)
1201 object = find_sti_class(record[inheritance_column]).allocate
1202
1203 object.instance_variable_set(:'@attributes', record)
1204 object.instance_variable_set(:'@attributes_cache', {})
1205
1206 object.send(:_run_find_callbacks)
1207 object.send(:_run_initialize_callbacks)
1208
1209 object
1210 end
1211
1212 def find_sti_class(type_name)
1213 if type_name.blank? || !columns_hash.include?(inheritance_column)
1214 self
1215 else
1216 begin
1217 compute_type(type_name)
1218 rescue NameError
1219 raise SubclassNotFound,
1220 "The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " +
1221 "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " +
1222 "Please rename this column if you didn't intend it to be used for storing the inheritance class " +
1223 "or overwrite #{name}.inheritance_column to use another column for that information."
1224 end
1225 end
1226 end
1227
1228 # Nest the type name in the same module as this class.
1229 # Bar is "MyApp::Business::Bar" relative to MyApp::Business::Foo
1230 def type_name_with_module(type_name)
1231 if store_full_sti_class
1232 type_name
1233 else
1234 (/^::/ =~ type_name) ? type_name : "#{parent.name}::#{type_name}"
1235 end
1236 end
1237
1238 def construct_finder_arel(options = {}, scope = nil)
1239 relation = options.is_a?(Hash) ? unscoped.apply_finder_options(options) : unscoped.merge(options)
1240 relation = scope.merge(relation) if scope
1241 relation
1242 end
1243
1244 def type_condition
1245 sti_column = arel_table[inheritance_column]
1246 condition = sti_column.eq(sti_name)
1247 subclasses.each{|subclass| condition = condition.or(sti_column.eq(subclass.sti_name)) }
1248
1249 condition
1250 end
1251
1252 # Guesses the table name, but does not decorate it with prefix and suffix information.
1253 def undecorated_table_name(class_name = base_class.name)
1254 table_name = class_name.to_s.demodulize.underscore
1255 table_name = table_name.pluralize if pluralize_table_names
1256 table_name
1257 end
1258
1259 # Enables dynamic finders like <tt>find_by_user_name(user_name)</tt> and <tt>find_by_user_name_and_password(user_name, password)</tt>
1260 # that are turned into <tt>where(:user_name => user_name).first</tt> and <tt>where(:user_name => user_name, :password => :password).first</tt>
1261 # respectively. Also works for <tt>all</tt> by using <tt>find_all_by_amount(50)</tt> that is turned into <tt>where(:amount => 50).all</tt>.
1262 #
1263 # It's even possible to use all the additional parameters to +find+. For example, the full interface for +find_all_by_amount+
1264 # is actually <tt>find_all_by_amount(amount, options)</tt>.
1265 #
1266 # Also enables dynamic scopes like scoped_by_user_name(user_name) and scoped_by_user_name_and_password(user_name, password) that
1267 # are turned into scoped(:conditions => ["user_name = ?", user_name]) and scoped(:conditions => ["user_name = ? AND password = ?", user_name, password])
1268 # respectively.
1269 #
1270 # Each dynamic finder, scope or initializer/creator is also defined in the class after it is first invoked, so that future
1271 # attempts to use it do not run through method_missing.
1272 def method_missing(method_id, *arguments, &block)
1273 if match = DynamicFinderMatch.match(method_id)
1274 attribute_names = match.attribute_names
1275 super unless all_attributes_exists?(attribute_names)
1276 if match.finder?
1277 options = arguments.extract_options!
1278 relation = options.any? ? construct_finder_arel(options, current_scoped_methods) : scoped
1279 relation.send :find_by_attributes, match, attribute_names, *arguments
1280 elsif match.instantiator?
1281 scoped.send :find_or_instantiator_by_attributes, match, attribute_names, *arguments, &block
1282 end
1283 elsif match = DynamicScopeMatch.match(method_id)
1284 attribute_names = match.attribute_names
1285 super unless all_attributes_exists?(attribute_names)
1286 if match.scope?
1287 self.class_eval %{
1288 def self.#{method_id}(*args) # def self.scoped_by_user_name_and_password(*args)
1289 options = args.extract_options! # options = args.extract_options!
1290 attributes = construct_attributes_from_arguments( # attributes = construct_attributes_from_arguments(
1291 [:#{attribute_names.join(',:')}], args # [:user_name, :password], args
1292 ) # )
1293 #
1294 scoped(:conditions => attributes) # scoped(:conditions => attributes)
1295 end # end
1296 }, __FILE__, __LINE__
1297 send(method_id, *arguments)
1298 end
1299 else
1300 super
1301 end
1302 end
1303
1304 def construct_attributes_from_arguments(attribute_names, arguments)
1305 attributes = {}
1306 attribute_names.each_with_index { |name, idx| attributes[name] = arguments[idx] }
1307 attributes
1308 end
1309
1310 # Similar in purpose to +expand_hash_conditions_for_aggregates+.
1311 def expand_attribute_names_for_aggregates(attribute_names)
1312 expanded_attribute_names = []
1313 attribute_names.each do |attribute_name|
1314 unless (aggregation = reflect_on_aggregation(attribute_name.to_sym)).nil?
1315 aggregate_mapping(aggregation).each do |field_attr, aggregate_attr|
1316 expanded_attribute_names << field_attr
1317 end
1318 else
1319 expanded_attribute_names << attribute_name
1320 end
1321 end
1322 expanded_attribute_names
1323 end
1324
1325 def all_attributes_exists?(attribute_names)
1326 attribute_names = expand_attribute_names_for_aggregates(attribute_names)
1327 attribute_names.all? { |name| column_methods_hash.include?(name.to_sym) }
1328 end
1329
1330 def attribute_condition(quoted_column_name, argument)
1331 case argument
1332 when nil then "#{quoted_column_name} IS ?"
1333 when Array, ActiveRecord::Associations::AssociationCollection, ActiveRecord::NamedScope::Scope then "#{quoted_column_name} IN (?)"
1334 when Range then if argument.exclude_end?
1335 "#{quoted_column_name} >= ? AND #{quoted_column_name} < ?"
1336 else
1337 "#{quoted_column_name} BETWEEN ? AND ?"
1338 end
1339 else "#{quoted_column_name} = ?"
1340 end
1341 end
1342
1343 protected
1344 # Scope parameters to method calls within the block. Takes a hash of method_name => parameters hash.
1345 # method_name may be <tt>:find</tt> or <tt>:create</tt>. <tt>:find</tt> parameters may include the <tt>:conditions</tt>, <tt>:joins</tt>,
1346 # <tt>:include</tt>, <tt>:offset</tt>, <tt>:limit</tt>, and <tt>:readonly</tt> options. <tt>:create</tt> parameters are an attributes hash.
1347 #
1348 # class Article < ActiveRecord::Base
1349 # def self.create_with_scope
1350 # with_scope(:find => { :conditions => "blog_id = 1" }, :create => { :blog_id => 1 }) do
1351 # find(1) # => SELECT * from articles WHERE blog_id = 1 AND id = 1
1352 # a = create(1)
1353 # a.blog_id # => 1
1354 # end
1355 # end
1356 # end
1357 #
1358 # In nested scopings, all previous parameters are overwritten by the innermost rule, with the exception of
1359 # <tt>:conditions</tt>, <tt>:include</tt>, and <tt>:joins</tt> options in <tt>:find</tt>, which are merged.
1360 #
1361 # <tt>:joins</tt> options are uniqued so multiple scopes can join in the same table without table aliasing
1362 # problems. If you need to join multiple tables, but still want one of the tables to be uniqued, use the
1363 # array of strings format for your joins.
1364 #
1365 # class Article < ActiveRecord::Base
1366 # def self.find_with_scope
1367 # with_scope(:find => { :conditions => "blog_id = 1", :limit => 1 }, :create => { :blog_id => 1 }) do
1368 # with_scope(:find => { :limit => 10 }) do
1369 # find(:all) # => SELECT * from articles WHERE blog_id = 1 LIMIT 10
1370 # end
1371 # with_scope(:find => { :conditions => "author_id = 3" }) do
1372 # find(:all) # => SELECT * from articles WHERE blog_id = 1 AND author_id = 3 LIMIT 1
1373 # end
1374 # end
1375 # end
1376 # end
1377 #
1378 # You can ignore any previous scopings by using the <tt>with_exclusive_scope</tt> method.
1379 #
1380 # class Article < ActiveRecord::Base
1381 # def self.find_with_exclusive_scope
1382 # with_scope(:find => { :conditions => "blog_id = 1", :limit => 1 }) do
1383 # with_exclusive_scope(:find => { :limit => 10 })
1384 # find(:all) # => SELECT * from articles LIMIT 10
1385 # end
1386 # end
1387 # end
1388 # end
1389 #
1390 # *Note*: the +:find+ scope also has effect on update and deletion methods,
1391 # like +update_all+ and +delete_all+.
1392 def with_scope(method_scoping = {}, action = :merge, &block)
1393 method_scoping = method_scoping.method_scoping if method_scoping.respond_to?(:method_scoping)
1394
1395 if method_scoping.is_a?(Hash)
1396 # Dup first and second level of hash (method and params).
1397 method_scoping = method_scoping.inject({}) do |hash, (method, params)|
1398 hash[method] = (params == true) ? params : params.dup
1399 hash
1400 end
1401
1402 method_scoping.assert_valid_keys([ :find, :create ])
1403 relation = construct_finder_arel(method_scoping[:find] || {})
1404
1405 if current_scoped_methods && current_scoped_methods.create_with_value && method_scoping[:create]
1406 scope_for_create = if action == :merge
1407 current_scoped_methods.create_with_value.merge(method_scoping[:create])
1408 else
1409 method_scoping[:create]
1410 end
1411
1412 relation = relation.create_with(scope_for_create)
1413 else
1414 scope_for_create = method_scoping[:create]
1415 scope_for_create ||= current_scoped_methods.create_with_value if current_scoped_methods
1416 relation = relation.create_with(scope_for_create) if scope_for_create
1417 end
1418
1419 method_scoping = relation
1420 end
1421
1422 method_scoping = current_scoped_methods.merge(method_scoping) if current_scoped_methods && action == :merge
1423
1424 self.scoped_methods << method_scoping
1425 begin
1426 yield
1427 ensure
1428 self.scoped_methods.pop
1429 end
1430 end
1431
1432 # Works like with_scope, but discards any nested properties.
1433 def with_exclusive_scope(method_scoping = {}, &block)
1434 with_scope(method_scoping, :overwrite, &block)
1435 end
1436
1437 def subclasses #:nodoc:
1438 @@subclasses[self] ||= []
1439 @@subclasses[self] + = @@subclasses[self].inject([]) {|list, subclass| list + subclass.subclasses }
1440 end
1441
1442 # Sets the default options for the model. The format of the
1443 # <tt>options</tt> argument is the same as in find.
1444 #
1445 # class Person < ActiveRecord::Base
1446 # default_scope :order => 'last_name, first_name'
1447 # end
1448 def default_scope(options = {})
1449 self.default_scoping << construct_finder_arel(options)
1450 end
1451
1452 def scoped_methods #:nodoc:
1453 key = :"#{self}_scoped_methods"
1454 Thread.current[key] = Thread.current[key].presence || self.default_scoping.dup
1455 end
1456
1457 def current_scoped_methods #:nodoc:
1458 scoped_methods.last
1459 end
1460
1461 # Returns the class type of the record using the current module as a prefix. So descendants of
1462 # MyApp::Business::Account would appear as MyApp::Business::AccountSubclass.
1463 def compute_type(type_name)
1464 modularized_name = type_name_with_module(type_name)
1465 silence_warnings do
1466 begin
1467 class_eval(modularized_name, __FILE__, __LINE__)
1468 rescue NameError
1469 class_eval(type_name, __FILE__, __LINE__)
1470 end
1471 end
1472 end
1473
1474 # Returns the class descending directly from ActiveRecord::Base or an
1475 # abstract class, if any, in the inheritance hierarchy.
1476 def class_of_active_record_descendant(klass)
1477 if klass.superclass == Base || klass.superclass.abstract_class?
1478 klass
1479 elsif klass.superclass.nil?
1480 raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord"
1481 else
1482 class_of_active_record_descendant(klass.superclass)
1483 end
1484 end
1485
1486 # Returns the name of the class descending directly from Active Record in the inheritance hierarchy.
1487 def class_name_of_active_record_descendant(klass) #:nodoc:
1488 klass.base_class.name
1489 end
1490
1491 # Accepts an array, hash, or string of SQL conditions and sanitizes
1492 # them into a valid SQL fragment for a WHERE clause.
1493 # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
1494 # { :name => "foo'bar", :group_id => 4 } returns "name='foo''bar' and group_id='4'"
1495 # "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'"
1496 def sanitize_sql_for_conditions(condition, table_name = self.table_name)
1497 return nil if condition.blank?
1498
1499 case condition
1500 when Array; sanitize_sql_array(condition)
1501 when Hash; sanitize_sql_hash_for_conditions(condition, table_name)
1502 else condition
1503 end
1504 end
1505 alias_method :sanitize_sql, :sanitize_sql_for_conditions
1506
1507 # Accepts an array, hash, or string of SQL conditions and sanitizes
1508 # them into a valid SQL fragment for a SET clause.
1509 # { :name => nil, :group_id => 4 } returns "name = NULL , group_id='4'"
1510 def sanitize_sql_for_assignment(assignments)
1511 case assignments
1512 when Array; sanitize_sql_array(assignments)
1513 when Hash; sanitize_sql_hash_for_assignment(assignments)
1514 else assignments
1515 end
1516 end
1517
1518 def aggregate_mapping(reflection)
1519 mapping = reflection.options[:mapping] || [reflection.name, reflection.name]
1520 mapping.first.is_a?(Array) ? mapping : [mapping]
1521 end
1522
1523 # Accepts a hash of SQL conditions and replaces those attributes
1524 # that correspond to a +composed_of+ relationship with their expanded
1525 # aggregate attribute values.
1526 # Given:
1527 # class Person < ActiveRecord::Base
1528 # composed_of :address, :class_name => "Address",
1529 # :mapping => [%w(address_street street), %w(address_city city)]
1530 # end
1531 # Then:
1532 # { :address => Address.new("813 abc st.", "chicago") }
1533 # # => { :address_street => "813 abc st.", :address_city => "chicago" }
1534 def expand_hash_conditions_for_aggregates(attrs)
1535 expanded_attrs = {}
1536 attrs.each do |attr, value|
1537 unless (aggregation = reflect_on_aggregation(attr.to_sym)).nil?
1538 mapping = aggregate_mapping(aggregation)
1539 mapping.each do |field_attr, aggregate_attr|
1540 if mapping.size == 1 && !value.respond_to?(aggregate_attr)
1541 expanded_attrs[field_attr] = value
1542 else
1543 expanded_attrs[field_attr] = value.send(aggregate_attr)
1544 end
1545 end
1546 else
1547 expanded_attrs[attr] = value
1548 end
1549 end
1550 expanded_attrs
1551 end
1552
1553 # Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause.
1554 # { :name => "foo'bar", :group_id => 4 }
1555 # # => "name='foo''bar' and group_id= 4"
1556 # { :status => nil, :group_id => [1,2,3] }
1557 # # => "status IS NULL and group_id IN (1,2,3)"
1558 # { :age => 13..18 }
1559 # # => "age BETWEEN 13 AND 18"
1560 # { 'other_records.id' => 7 }
1561 # # => "`other_records`.`id` = 7"
1562 # { :other_records => { :id => 7 } }
1563 # # => "`other_records`.`id` = 7"
1564 # And for value objects on a composed_of relationship:
1565 # { :address => Address.new("123 abc st.", "chicago") }
1566 # # => "address_street='123 abc st.' and address_city='chicago'"
1567 def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name)
1568 attrs = expand_hash_conditions_for_aggregates(attrs)
1569
1570 table = Arel::Table.new(self.table_name, :engine => arel_engine, :as => default_table_name)
1571 builder = PredicateBuilder.new(arel_engine)
1572 builder.build_from_hash(attrs, table).map(&:to_sql).join(' AND ')
1573 end
1574 alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions
1575
1576 # Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause.
1577 # { :status => nil, :group_id => 1 }
1578 # # => "status = NULL , group_id = 1"
1579 def sanitize_sql_hash_for_assignment(attrs)
1580 attrs.map do |attr, value|
1581 "#{connection.quote_column_name(attr)} = #{quote_bound_value(value)}"
1582 end.join(', ')
1583 end
1584
1585 # Accepts an array of conditions. The array has each value
1586 # sanitized and interpolated into the SQL statement.
1587 # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
1588 def sanitize_sql_array(ary)
1589 statement, *values = ary
1590 if values.first.is_a?(Hash) and statement =~ /:\w+/
1591 replace_named_bind_variables(statement, values.first)
1592 elsif statement.include?('?')
1593 replace_bind_variables(statement, values)
1594 else
1595 statement % values.collect { |value| connection.quote_string(value.to_s) }
1596 end
1597 end
1598
1599 alias_method :sanitize_conditions, :sanitize_sql
1600
1601 def replace_bind_variables(statement, values) #:nodoc:
1602 raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size)
1603 bound = values.dup
1604 statement.gsub('?') { quote_bound_value(bound.shift) }
1605 end
1606
1607 def replace_named_bind_variables(statement, bind_vars) #:nodoc:
1608 statement.gsub(/(:?):([a-zA-Z]\w*)/) do
1609 if $1 == ':' # skip postgresql casts
1610 $& # return the whole match
1611 elsif bind_vars.include?(match = $2.to_sym)
1612 quote_bound_value(bind_vars[match])
1613 else
1614 raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}"
1615 end
1616 end
1617 end
1618
1619 def expand_range_bind_variables(bind_vars) #:nodoc:
1620 expanded = []
1621
1622 bind_vars.each do |var|
1623 next if var.is_a?(Hash)
1624
1625 if var.is_a?(Range)
1626 expanded << var.first
1627 expanded << var.last
1628 else
1629 expanded << var
1630 end
1631 end
1632
1633 expanded
1634 end
1635
1636 def quote_bound_value(value) #:nodoc:
1637 if value.respond_to?(:map) && !value.acts_like?(:string)
1638 if value.respond_to?(:empty?) && value.empty?
1639 connection.quote(nil)
1640 else
1641 value.map { |v| connection.quote(v) }.join(',')
1642 end
1643 else
1644 connection.quote(value)
1645 end
1646 end
1647
1648 def raise_if_bind_arity_mismatch(statement, expected, provided) #:nodoc:
1649 unless expected == provided
1650 raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}"
1651 end
1652 end
1653
1654 def encode_quoted_value(value) #:nodoc:
1655 quoted_value = connection.quote(value)
1656 quoted_value = "'#{quoted_value[1..-2].gsub(/\'/, "\\\\'")}'" if quoted_value.include?("\\\'") # (for ruby mode) "
1657 quoted_value
1658 end
1659 end
1660
1661 public
1662 # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
1663 # attributes but not yet saved (pass a hash with key names matching the associated table column names).
1664 # In both instances, valid attribute keys are determined by the column names of the associated table --
1665 # hence you can't have attributes that aren't part of the table columns.
1666 def initialize(attributes = nil)
1667 @attributes = attributes_from_column_definition
1668 @attributes_cache = {}
1669 @new_record = true
1670 ensure_proper_type
1671 self.attributes = attributes unless attributes.nil?
1672
1673 if scope = self.class.send(:current_scoped_methods)
1674 create_with = scope.scope_for_create
1675 create_with.each { |att,value| self.send("#{att}=", value) } if create_with
1676 end
1677
1678 result = yield self if block_given?
1679 _run_initialize_callbacks
1680 result
1681 end
1682
1683 # Cloned objects have no id assigned and are treated as new records. Note that this is a "shallow" clone
1684 # as it copies the object's attributes only, not its associations. The extent of a "deep" clone is
1685 # application specific and is therefore left to the application to implement according to its need.
1686 def initialize_copy(other)
1687 # Think the assertion which fails if the after_initialize callback goes at the end of the method is wrong. The
1688 # deleted clone method called new which therefore called the after_initialize callback. It then went on to copy
1689 # over the attributes. But if it's copying the attributes afterwards then it hasn't finished initializing right?
1690 # For example in the test suite the topic model's after_initialize method sets the author_email_address to
1691 # test@test.com. I would have thought this would mean that all cloned models would have an author email address
1692 # of test@test.com. However the test_clone test method seems to test that this is not the case. As a result the
1693 # after_initialize callback has to be run *before* the copying of the atrributes rather than afterwards in order
1694 # for all tests to pass. This makes no sense to me.
1695 callback(:after_initialize) if respond_to_without_attributes?(:after_initialize)
1696 cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast)
1697 cloned_attributes.delete(self.class.primary_key)
1698 @attributes = cloned_attributes
1699 clear_aggregation_cache
1700 @attributes_cache = {}
1701 @new_record = true
1702 ensure_proper_type
1703
1704 if scope = self.class.send(:current_scoped_methods)
1705 create_with = scope.scope_for_create
1706 create_with.each { |att,value| self.send("#{att}=", value) } if create_with
1707 end
1708 end
1709
1710 # Returns a String, which Action Pack uses for constructing an URL to this
1711 # object. The default implementation returns this record's id as a String,
1712 # or nil if this record's unsaved.
1713 #
1714 # For example, suppose that you have a User model, and that you have a
1715 # <tt>map.resources :users</tt> route. Normally, +user_path+ will
1716 # construct a path with the user object's 'id' in it:
1717 #
1718 # user = User.find_by_name('Phusion')
1719 # user_path(user) # => "/users/1"
1720 #
1721 # You can override +to_param+ in your model to make +user_path+ construct
1722 # a path using the user's name instead of the user's id:
1723 #
1724 # class User < ActiveRecord::Base
1725 # def to_param # overridden
1726 # name
1727 # end
1728 # end
1729 #
1730 # user = User.find_by_name('Phusion')
1731 # user_path(user) # => "/users/Phusion"
1732 def to_param
1733 # We can't use alias_method here, because method 'id' optimizes itself on the fly.
1734 (id = self.id) ? id.to_s : nil # Be sure to stringify the id for routes
1735 end
1736
1737 # Returns a cache key that can be used to identify this record.
1738 #
1739 # ==== Examples
1740 #
1741 # Product.new.cache_key # => "products/new"
1742 # Product.find(5).cache_key # => "products/5" (updated_at not available)
1743 # Person.find(5).cache_key # => "people/5-20071224150000" (updated_at available)
1744 def cache_key
1745 case
1746 when new_record?
1747 "#{self.class.model_name.cache_key}/new"
1748 when timestamp = self[:updated_at]
1749 "#{self.class.model_name.cache_key}/#{id}-#{timestamp.to_s(:number)}"
1750 else
1751 "#{self.class.model_name.cache_key}/#{id}"
1752 end
1753 end
1754
1755 def quoted_id #:nodoc:
1756 quote_value(id, column_for_attribute(self.class.primary_key))
1757 end
1758
1759 # Returns true if this object hasn't been saved yet -- that is, a record for the object doesn't exist yet; otherwise, returns false.
1760 def new_record?
1761 @new_record || false
1762 end
1763
1764 # Returns true if this object has been destroyed, otherwise returns false.
1765 def destroyed?
1766 @destroyed || false
1767 end
1768
1769 # :call-seq:
1770 # save(options)
1771 #
1772 # Saves the model.
1773 #
1774 # If the model is new a record gets created in the database, otherwise
1775 # the existing record gets updated.
1776 #
1777 # By default, save always run validations. If any of them fail the action
1778 # is cancelled and +save+ returns +false+. However, if you supply
1779 # :validate => false, validations are bypassed altogether. See
1780 # ActiveRecord::Validations for more information.
1781 #
1782 # There's a series of callbacks associated with +save+. If any of the
1783 # <tt>before_*</tt> callbacks return +false+ the action is cancelled and
1784 # +save+ returns +false+. See ActiveRecord::Callbacks for further
1785 # details.
1786 def save
1787 create_or_update
1788 end
1789
1790 # Saves the model.
1791 #
1792 # If the model is new a record gets created in the database, otherwise
1793 # the existing record gets updated.
1794 #
1795 # With <tt>save!</tt> validations always run. If any of them fail
1796 # ActiveRecord::RecordInvalid gets raised. See ActiveRecord::Validations
1797 # for more information.
1798 #
1799 # There's a series of callbacks associated with <tt>save!</tt>. If any of
1800 # the <tt>before_*</tt> callbacks return +false+ the action is cancelled
1801 # and <tt>save!</tt> raises ActiveRecord::RecordNotSaved. See
1802 # ActiveRecord::Callbacks for further details.
1803 def save!
1804 create_or_update || raise(RecordNotSaved)
1805 end
1806
1807 # Deletes the record in the database and freezes this instance to
1808 # reflect that no changes should be made (since they can't be
1809 # persisted). Returns the frozen instance.
1810 #
1811 # The row is simply removed with a SQL +DELETE+ statement on the
1812 # record's primary key, and no callbacks are executed.
1813 #
1814 # To enforce the object's +before_destroy+ and +after_destroy+
1815 # callbacks, Observer methods, or any <tt>:dependent</tt> association
1816 # options, use <tt>#destroy</tt>.
1817 def delete
1818 self.class.delete(id) unless new_record?
1819 @destroyed = true
1820 freeze
1821 end
1822
1823 # Deletes the record in the database and freezes this instance to reflect that no changes should
1824 # be made (since they can't be persisted).
1825 def destroy
1826 unless new_record?
1827 self.class.unscoped.where(self.class.arel_table[self.class.primary_key].eq(id)).delete_all
1828 end
1829
1830 @destroyed = true
1831 freeze
1832 end
1833
1834 # Returns an instance of the specified +klass+ with the attributes of the current record. This is mostly useful in relation to
1835 # single-table inheritance structures where you want a subclass to appear as the superclass. This can be used along with record
1836 # identification in Action Pack to allow, say, <tt>Client < Company</tt> to do something like render <tt>:partial => @client.becomes(Company)</tt>
1837 # to render that instance using the companies/company partial instead of clients/client.
1838 #
1839 # Note: The new instance will share a link to the same attributes as the original class. So any change to the attributes in either
1840 # instance will affect the other.
1841 def becomes(klass)
1842 became = klass.new
1843 became.instance_variable_set("@attributes", @attributes)
1844 became.instance_variable_set("@attributes_cache", @attributes_cache)
1845 became.instance_variable_set("@new_record", new_record?)
1846 became
1847 end
1848
1849 # Updates a single attribute and saves the record without going through the normal validation procedure.
1850 # This is especially useful for boolean flags on existing records. The regular +update_attribute+ method
1851 # in Base is replaced with this when the validations module is mixed in, which it is by default.
1852 def update_attribute(name, value)
1853 send(name.to_s + '=', value)
1854 save(:validate => false)
1855 end
1856
1857 # Updates all the attributes from the passed-in Hash and saves the record. If the object is invalid, the saving will
1858 # fail and false will be returned.
1859 def update_attributes(attributes)
1860 self.attributes = attributes
1861 save
1862 end
1863
1864 # Updates an object just like Base.update_attributes but calls save! instead of save so an exception is raised if the record is invalid.
1865 def update_attributes!(attributes)
1866 self.attributes = attributes
1867 save!
1868 end
1869
1870 # Initializes +attribute+ to zero if +nil+ and adds the value passed as +by+ (default is 1).
1871 # The increment is performed directly on the underlying attribute, no setter is invoked.
1872 # Only makes sense for number-based attributes. Returns +self+.
1873 def increment(attribute, by = 1)
1874 self[attribute] ||= 0
1875 self[attribute] += by
1876 self
1877 end
1878
1879 # Wrapper around +increment+ that saves the record. This method differs from
1880 # its non-bang version in that it passes through the attribute setter.
1881 # Saving is not subjected to validation checks. Returns +true+ if the
1882 # record could be saved.
1883 def increment!(attribute, by = 1)
1884 increment(attribute, by).update_attribute(attribute, self[attribute])
1885 end
1886
1887 # Initializes +attribute+ to zero if +nil+ and subtracts the value passed as +by+ (default is 1).
1888 # The decrement is performed directly on the underlying attribute, no setter is invoked.
1889 # Only makes sense for number-based attributes. Returns +self+.
1890 def decrement(attribute, by = 1)
1891 self[attribute] ||= 0
1892 self[attribute] -= by
1893 self
1894 end
1895
1896 # Wrapper around +decrement+ that saves the record. This method differs from
1897 # its non-bang version in that it passes through the attribute setter.
1898 # Saving is not subjected to validation checks. Returns +true+ if the
1899 # record could be saved.
1900 def decrement!(attribute, by = 1)
1901 decrement(attribute, by).update_attribute(attribute, self[attribute])
1902 end
1903
1904 # Assigns to +attribute+ the boolean opposite of <tt>attribute?</tt>. So
1905 # if the predicate returns +true+ the attribute will become +false+. This
1906 # method toggles directly the underlying value without calling any setter.
1907 # Returns +self+.
1908 def toggle(attribute)
1909 self[attribute] = !send("#{attribute}?")
1910 self
1911 end
1912
1913 # Wrapper around +toggle+ that saves the record. This method differs from
1914 # its non-bang version in that it passes through the attribute setter.
1915 # Saving is not subjected to validation checks. Returns +true+ if the
1916 # record could be saved.
1917 def toggle!(attribute)
1918 toggle(attribute).update_attribute(attribute, self[attribute])
1919 end
1920
1921 # Reloads the attributes of this object from the database.
1922 # The optional options argument is passed to find when reloading so you
1923 # may do e.g. record.reload(:lock => true) to reload the same record with
1924 # an exclusive row lock.
1925 def reload(options = nil)
1926 clear_aggregation_cache
1927 clear_association_cache
1928 @attributes.update(self.class.find(self.id, options).instance_variable_get('@attributes'))
1929 @attributes_cache = {}
1930 self
1931 end
1932
1933 # Returns true if the given attribute is in the attributes hash
1934 def has_attribute?(attr_name)
1935 @attributes.has_key?(attr_name.to_s)
1936 end
1937
1938 # Returns an array of names for the attributes available on this object sorted alphabetically.
1939 def attribute_names
1940 @attributes.keys.sort
1941 end
1942
1943 # Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
1944 # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
1945 # (Alias for the protected read_attribute method).
1946 def [](attr_name)
1947 read_attribute(attr_name)
1948 end
1949
1950 # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
1951 # (Alias for the protected write_attribute method).
1952 def []=(attr_name, value)
1953 write_attribute(attr_name, value)
1954 end
1955
1956 # Allows you to set all the attributes at once by passing in a hash with keys
1957 # matching the attribute names (which again matches the column names).
1958 #
1959 # If +guard_protected_attributes+ is true (the default), then sensitive
1960 # attributes can be protected from this form of mass-assignment by using
1961 # the +attr_protected+ macro. Or you can alternatively specify which
1962 # attributes *can* be accessed with the +attr_accessible+ macro. Then all the
1963 # attributes not included in that won't be allowed to be mass-assigned.
1964 #
1965 # class User < ActiveRecord::Base
1966 # attr_protected :is_admin
1967 # end
1968 #
1969 # user = User.new
1970 # user.attributes = { :username => 'Phusion', :is_admin => true }
1971 # user.username # => "Phusion"
1972 # user.is_admin? # => false
1973 #
1974 # user.send(:attributes=, { :username => 'Phusion', :is_admin => true }, false)
1975 # user.is_admin? # => true
1976 def attributes=(new_attributes, guard_protected_attributes = true)
1977 return if new_attributes.nil?
1978 attributes = new_attributes.dup
1979 attributes.stringify_keys!
1980
1981 multi_parameter_attributes = []
1982 attributes = remove_attributes_protected_from_mass_assignment(attributes) if guard_protected_attributes
1983
1984 attributes.each do |k, v|
1985 if k.include?("(")
1986 multi_parameter_attributes << [ k, v ]
1987 else
1988 respond_to?(:"#{k}=") ? send(:"#{k}=", v) : raise(UnknownAttributeError, "unknown attribute: #{k}")
1989 end
1990 end
1991
1992 assign_multiparameter_attributes(multi_parameter_attributes)
1993 end
1994
1995 # Returns a hash of all the attributes with their names as keys and the values of the attributes as values.
1996 def attributes
1997 self.attribute_names.inject({}) do |attrs, name|
1998 attrs[name] = read_attribute(name)
1999 attrs
2000 end
2001 end
2002
2003 # Returns an <tt>#inspect</tt>-like string for the value of the
2004 # attribute +attr_name+. String attributes are elided after 50
2005 # characters, and Date and Time attributes are returned in the
2006 # <tt>:db</tt> format. Other attributes return the value of
2007 # <tt>#inspect</tt> without modification.
2008 #
2009 # person = Person.create!(:name => "David Heinemeier Hansson " * 3)
2010 #
2011 # person.attribute_for_inspect(:name)
2012 # # => '"David Heinemeier Hansson David Heinemeier Hansson D..."'
2013 #
2014 # person.attribute_for_inspect(:created_at)
2015 # # => '"2009-01-12 04:48:57"'
2016 def attribute_for_inspect(attr_name)
2017 value = read_attribute(attr_name)
2018
2019 if value.is_a?(String) && value.length > 50
2020 "#{value[0..50]}...".inspect
2021 elsif value.is_a?(Date) || value.is_a?(Time)
2022 %("#{value.to_s(:db)}")
2023 else
2024 value.inspect
2025 end
2026 end
2027
2028 # Returns true if the specified +attribute+ has been set by the user or by a database load and is neither
2029 # nil nor empty? (the latter only applies to objects that respond to empty?, most notably Strings).
2030 def attribute_present?(attribute)
2031 value = read_attribute(attribute)
2032 !value.blank?
2033 end
2034
2035 # Returns the column object for the named attribute.
2036 def column_for_attribute(name)
2037 self.class.columns_hash[name.to_s]
2038 end
2039
2040 # Returns true if the +comparison_object+ is the same object, or is of the same type and has the same id.
2041 def ==(comparison_object)
2042 comparison_object.equal?(self) ||
2043 (comparison_object.instance_of?(self.class) &&
2044 comparison_object.id == id &&
2045 !comparison_object.new_record?)
2046 end
2047
2048 # Delegates to ==
2049 def eql?(comparison_object)
2050 self == (comparison_object)
2051 end
2052
2053 # Delegates to id in order to allow two records of the same type and id to work with something like:
2054 # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
2055 def hash
2056 id.hash
2057 end
2058
2059 # Freeze the attributes hash such that associations are still accessible, even on destroyed records.
2060 def freeze
2061 @attributes.freeze; self
2062 end
2063
2064 # Returns +true+ if the attributes hash has been frozen.
2065 def frozen?
2066 @attributes.frozen?
2067 end
2068
2069 # Returns duplicated record with unfreezed attributes.
2070 def dup
2071 obj = super
2072 obj.instance_variable_set('@attributes', instance_variable_get('@attributes').dup)
2073 obj
2074 end
2075
2076 # Returns +true+ if the record is read only. Records loaded through joins with piggy-back
2077 # attributes will be marked as read only since they cannot be saved.
2078 def readonly?
2079 defined?(@readonly) && @readonly == true
2080 end
2081
2082 # Marks this record as read only.
2083 def readonly!
2084 @readonly = true
2085 end
2086
2087 # Returns the contents of the record as a nicely formatted string.
2088 def inspect
2089 attributes_as_nice_string = self.class.column_names.collect { |name|
2090 if has_attribute?(name) || new_record?
2091 "#{name}: #{attribute_for_inspect(name)}"
2092 end
2093 }.compact.join(", ")
2094 "#<#{self.class} #{attributes_as_nice_string}>"
2095 end
2096
2097 protected
2098 def clone_attributes(reader_method = :read_attribute, attributes = {})
2099 self.attribute_names.inject(attributes) do |attrs, name|
2100 attrs[name] = clone_attribute_value(reader_method, name)
2101 attrs
2102 end
2103 end
2104
2105 def clone_attribute_value(reader_method, attribute_name)
2106 value = send(reader_method, attribute_name)
2107 value.duplicable? ? value.clone : value
2108 rescue TypeError, NoMethodError
2109 value
2110 end
2111
2112 private
2113 def create_or_update
2114 raise ReadOnlyRecord if readonly?
2115 result = new_record? ? create : update
2116 result != false
2117 end
2118
2119 # Updates the associated record with values matching those of the instance attributes.
2120 # Returns the number of affected rows.
2121 def update(attribute_names = @attributes.keys)
2122 attributes_with_values = arel_attributes_values(false, false, attribute_names)
2123 return 0 if attributes_with_values.empty?
2124 self.class.unscoped.where(self.class.arel_table[self.class.primary_key].eq(id)).arel.update(attributes_with_values)
2125 end
2126
2127 # Creates a record with values matching those of the instance attributes
2128 # and returns its id.
2129 def create
2130 if self.id.nil? && connection.prefetch_primary_key?(self.class.table_name)
2131 self.id = connection.next_sequence_value(self.class.sequence_name)
2132 end
2133
2134 attributes_values = arel_attributes_values
2135
2136 new_id = if attributes_values.empty?
2137 self.class.unscoped.insert connection.empty_insert_statement_value
2138 else
2139 self.class.unscoped.insert attributes_values
2140 end
2141
2142 self.id ||= new_id
2143
2144 @new_record = false
2145 id
2146 end
2147
2148 # Sets the attribute used for single table inheritance to this class name if this is not the ActiveRecord::Base descendant.
2149 # Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to do Reply.new without having to
2150 # set <tt>Reply[Reply.inheritance_column] = "Reply"</tt> yourself. No such attribute would be set for objects of the
2151 # Message class in that example.
2152 def ensure_proper_type
2153 unless self.class.descends_from_active_record?
2154 write_attribute(self.class.inheritance_column, self.class.sti_name)
2155 end
2156 end
2157
2158 def remove_attributes_protected_from_mass_assignment(attributes)
2159 safe_attributes =
2160 if self.class.accessible_attributes.nil? && self.class.protected_attributes.nil?
2161 attributes.reject { |key, value| attributes_protected_by_default.include?(key.gsub(/\(.+/, "")) }
2162 elsif self.class.protected_attributes.nil?
2163 attributes.reject { |key, value| !self.class.accessible_attributes.include?(key.gsub(/\(.+/, "")) || attributes_protected_by_default.include?(key.gsub(/\(.+/, "")) }
2164 elsif self.class.accessible_attributes.nil?
2165 attributes.reject { |key, value| self.class.protected_attributes.include?(key.gsub(/\(.+/,"")) || attributes_protected_by_default.include?(key.gsub(/\(.+/, "")) }
2166 else
2167 raise "Declare either attr_protected or attr_accessible for #{self.class}, but not both."
2168 end
2169
2170 removed_attributes = attributes.keys - safe_attributes.keys
2171
2172 if removed_attributes.any?
2173 log_protected_attribute_removal(removed_attributes)
2174 end
2175
2176 safe_attributes
2177 end
2178
2179 # Removes attributes which have been marked as readonly.
2180 def remove_readonly_attributes(attributes)
2181 unless self.class.readonly_attributes.nil?
2182 attributes.delete_if { |key, value| self.class.readonly_attributes.include?(key.gsub(/\(.+/,"")) }
2183 else
2184 attributes
2185 end
2186 end
2187
2188 def log_protected_attribute_removal(*attributes)
2189 if logger
2190 logger.debug "WARNING: Can't mass-assign these protected attributes: #{attributes.join(', ')}"
2191 end
2192 end
2193
2194 # The primary key and inheritance column can never be set by mass-assignment for security reasons.
2195 def attributes_protected_by_default
2196 default = [ self.class.primary_key, self.class.inheritance_column ]
2197 default << 'id' unless self.class.primary_key.eql? 'id'
2198 default
2199 end
2200
2201 # Returns a copy of the attributes hash where all the values have been safely quoted for use in
2202 # an SQL statement.
2203 def attributes_with_quotes(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys)
2204 quoted = {}
2205 connection = self.class.connection
2206 attribute_names.each do |name|
2207 if (column = column_for_attribute(name)) && (include_primary_key || !column.primary)
2208 value = read_attribute(name)
2209
2210 # We need explicit to_yaml because quote() does not properly convert Time/Date fields to YAML.
2211 if value && self.class.serialized_attributes.has_key?(name) && (value.acts_like?(:date) || value.acts_like?(:time))
2212 value = value.to_yaml
2213 end
2214
2215 quoted[name] = connection.quote(value, column)
2216 end
2217 end
2218 include_readonly_attributes ? quoted : remove_readonly_attributes(quoted)
2219 end
2220
2221 # Returns a copy of the attributes hash where all the values have been safely quoted for use in
2222 # an Arel insert/update method.
2223 def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys)
2224 attrs = {}
2225 attribute_names.each do |name|
2226 if (column = column_for_attribute(name)) && (include_primary_key || !column.primary)
2227
2228 if include_readonly_attributes || (!include_readonly_attributes && !self.class.readonly_attributes.include?(name))
2229 value = read_attribute(name)
2230
2231 if value && ((self.class.serialized_attributes.has_key?(name) && (value.acts_like?(:date) || value.acts_like?(:time))) || value.is_a?(Hash) || value.is_a?(Array))
2232 value = value.to_yaml
2233 end
2234 attrs[self.class.arel_table[name]] = value
2235 end
2236 end
2237 end
2238 attrs
2239 end
2240
2241 # Quote strings appropriately for SQL statements.
2242 def quote_value(value, column = nil)
2243 self.class.connection.quote(value, column)
2244 end
2245
2246 # Interpolate custom SQL string in instance context.
2247 # Optional record argument is meant for custom insert_sql.
2248 def interpolate_sql(sql, record = nil)
2249 instance_eval("%@#{sql.gsub('@', '\@')}@")
2250 end
2251
2252 # Initializes the attributes array with keys matching the columns from the linked table and
2253 # the values matching the corresponding default value of that column, so
2254 # that a new instance, or one populated from a passed-in Hash, still has all the attributes
2255 # that instances loaded from the database would.
2256 def attributes_from_column_definition
2257 self.class.columns.inject({}) do |attributes, column|
2258 attributes[column.name] = column.default unless column.name == self.class.primary_key
2259 attributes
2260 end
2261 end
2262
2263 # Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done
2264 # by calling new on the column type or aggregation type (through composed_of) object with these parameters.
2265 # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
2266 # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
2267 # parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, f for Float,
2268 # s for String, and a for Array. If all the values for a given attribute are empty, the attribute will be set to nil.
2269 def assign_multiparameter_attributes(pairs)
2270 execute_callstack_for_multiparameter_attributes(
2271 extract_callstack_for_multiparameter_attributes(pairs)
2272 )
2273 end
2274
2275 def instantiate_time_object(name, values)
2276 if self.class.send(:create_time_zone_conversion_attribute?, name, column_for_attribute(name))
2277 Time.zone.local(*values)
2278 else
2279 Time.time_with_datetime_fallback(@@default_timezone, *values)
2280 end
2281 end
2282
2283 def execute_callstack_for_multiparameter_attributes(callstack)
2284 errors = []
2285 callstack.each do |name, values_with_empty_parameters|
2286 begin
2287 klass = (self.class.reflect_on_aggregation(name.to_sym) || column_for_attribute(name)).klass
2288 # in order to allow a date to be set without a year, we must keep the empty values.
2289 # Otherwise, we wouldn't be able to distinguish it from a date with an empty day.
2290 values = values_with_empty_parameters.reject(&:nil?)
2291
2292 if values.empty?
2293 send(name + "=", nil)
2294 else
2295
2296 value = if Time == klass
2297 instantiate_time_object(name, values)
2298 elsif Date == klass
2299 begin
2300 values = values_with_empty_parameters.collect do |v| v.nil? ? 1 : v end
2301 Date.new(*values)
2302 rescue ArgumentError => ex # if Date.new raises an exception on an invalid date
2303 instantiate_time_object(name, values).to_date # we instantiate Time object and convert it back to a date thus using Time's logic in handling invalid dates
2304 end
2305 else
2306 klass.new(*values)
2307 end
2308
2309 send(name + "=", value)
2310 end
2311 rescue => ex
2312 errors << AttributeAssignmentError.new("error on assignment #{values.inspect} to #{name}", ex, name)
2313 end
2314 end
2315 unless errors.empty?
2316 raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes"
2317 end
2318 end
2319
2320 def extract_callstack_for_multiparameter_attributes(pairs)
2321 attributes = { }
2322
2323 for pair in pairs
2324 multiparameter_name, value = pair
2325 attribute_name = multiparameter_name.split("(").first
2326 attributes[attribute_name] = [] unless attributes.include?(attribute_name)
2327
2328 parameter_value = value.empty? ? nil : type_cast_attribute_value(multiparameter_name, value)
2329 attributes[attribute_name] << [ find_parameter_position(multiparameter_name), parameter_value ]
2330 end
2331
2332 attributes.each { |name, values| attributes[name] = values.sort_by{ |v| v.first }.collect { |v| v.last } }
2333 end
2334
2335 def type_cast_attribute_value(multiparameter_name, value)
2336 multiparameter_name =~ /\([0-9]*([if])\)/ ? value.send("to_" + $1) : value
2337 end
2338
2339 def find_parameter_position(multiparameter_name)
2340 multiparameter_name.scan(/\(([0-9]*).*\)/).first.first
2341 end
2342
2343 # Returns a comma-separated pair list, like "key1 = val1, key2 = val2".
2344 def comma_pair_list(hash)
2345 hash.inject([]) { |list, pair| list << "#{pair.first} = #{pair.last}" }.join(", ")
2346 end
2347
2348 def quote_columns(quoter, hash)
2349 hash.inject({}) do |quoted, (name, value)|
2350 quoted[quoter.quote_column_name(name)] = value
2351 quoted
2352 end
2353 end
2354
2355 def quoted_comma_pair_list(quoter, hash)
2356 comma_pair_list(quote_columns(quoter, hash))
2357 end
2358
2359 def convert_number_column_value(value)
2360 if value == false
2361 0
2362 elsif value == true
2363 1
2364 elsif value.is_a?(String) && value.blank?
2365 nil
2366 else
2367 value
2368 end
2369 end
2370
2371 def object_from_yaml(string)
2372 return string unless string.is_a?(String) && string =~ /^---/
2373 YAML::load(string) rescue string
2374 end
2375 end
2376
2377 Base.class_eval do
2378 extend ActiveModel::Naming
2379 extend QueryCache::ClassMethods
2380 extend ActiveSupport::Benchmarkable
2381
2382 include Validations
2383 include Locking::Optimistic, Locking::Pessimistic
2384 include AttributeMethods
2385 include AttributeMethods::Read, AttributeMethods::Write, AttributeMethods::BeforeTypeCast, AttributeMethods::Query
2386 include AttributeMethods::PrimaryKey
2387 include AttributeMethods::TimeZoneConversion
2388 include AttributeMethods::Dirty
2389 include Callbacks, ActiveModel::Observing, Timestamp
2390 include Associations, AssociationPreload, NamedScope
2391 include ActiveModel::Conversion
2392
2393 # AutosaveAssociation needs to be included before Transactions, because we want
2394 # #save_with_autosave_associations to be wrapped inside a transaction.
2395 include AutosaveAssociation, NestedAttributes
2396
2397 include Aggregations, Transactions, Reflection, Batches, Serialization
2398
2399 end
2400 end
2401
2402 # TODO: Remove this and make it work with LAZY flag
2403 require 'active_record/connection_adapters/abstract_adapter'