PageRenderTime 62ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/activerecord/lib/active_record/base.rb

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