Skip to content
Newer
Older
100644 731 lines (679 sloc) 29.5 KB
59f3218 @tenderlove load and prefer psych as the YAML parser when it is available
tenderlove authored
1 begin
2 require 'psych'
3 rescue LoadError
4 end
5
db045db @dhh Initial
dhh authored
6 require 'yaml'
aabf909 @jeremy Correct reader method generation for primary key attribute: handle ca…
jeremy authored
7 require 'set'
a15e02d @josevalim Unify benchmark APIs.
josevalim authored
8 require 'active_support/benchmarkable'
f5d720f @jeremy Opt in to Dependencies
jeremy authored
9 require 'active_support/dependencies'
033e0a0 @josevalim ActiveRecord and ActionPack now use the new descendants implementation.
josevalim authored
10 require 'active_support/descendants_tracker'
5f222c5 @jeremy Remove 'core' fluff. Hookable ActiveSupport.load_all!
jeremy authored
11 require 'active_support/time'
bab1f91 @phs table_name_prefix and table_name_suffix are class_attributes instead …
phs authored
12 require 'active_support/core_ext/class/attribute'
e8550ee @jeremy Cherry-pick core extensions
jeremy authored
13 require 'active_support/core_ext/class/attribute_accessors'
14 require 'active_support/core_ext/class/delegating_attributes'
d7db6a8 @joshk class inheritable attributes is used no more! all internal use of cla…
joshk authored
15 require 'active_support/core_ext/class/attribute'
e8550ee @jeremy Cherry-pick core extensions
jeremy authored
16 require 'active_support/core_ext/array/extract_options'
17 require 'active_support/core_ext/hash/deep_merge'
18 require 'active_support/core_ext/hash/indifferent_access'
19 require 'active_support/core_ext/hash/slice'
20 require 'active_support/core_ext/string/behavior'
89978f1 @fxn moves Object#singleton_class to Kernel#singleton_class to match Ruby …
fxn authored
21 require 'active_support/core_ext/kernel/singleton_class'
a7fd564 @lifo Add Model.select/group/order/limit/joins/conditions/preload/eager_loa…
lifo authored
22 require 'active_support/core_ext/module/delegation'
4a8c880 @fxn refactors AR::Base#reset_table_name
fxn authored
23 require 'active_support/core_ext/module/introspection'
105f9b8 @fxn adds missing requires for Object#duplicable?
fxn authored
24 require 'active_support/core_ext/object/duplicable'
76f024a @fxn adds missing requires for Object#blank? and Object#present?
fxn authored
25 require 'active_support/core_ext/object/blank'
0b72a04 @jonleighton Deprecate set_table_name in favour of self.table_name= or defining yo…
jonleighton authored
26 require 'active_support/deprecation'
39d6f9e @wycats Make many parts of Rails lazy. In order to facilitate this,
wycats authored
27 require 'arel'
28 require 'active_record/errors'
6788db8 @josevalim Move Rails::LogSubscriber to ActiveSupport::LogSubscriber, allowing f…
josevalim authored
29 require 'active_record/log_subscriber'
cfeac38 @fxn implements a much faster auto EXPLAIN, closes #3843 [José Valim & Xav…
fxn authored
30 require 'active_record/explain_subscriber'
db045db @dhh Initial
dhh authored
31
32 module ActiveRecord #:nodoc:
606088d @eac Mass assignment security refactoring
eac authored
33 # = Active Record
4ad6103 @rizwanreza Adds title and basic description where needed.
rizwanreza authored
34 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
35 # Active Record objects don't specify their attributes directly, but rather infer them from
36 # the table definition with which they're linked. Adding, removing, and changing attributes
37 # and their type is done directly in the database. Any change is instantly reflected in the
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
38 # Active Record objects. The mapping that binds a given Active Record class to a certain
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
39 # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
40 #
20333be @tilsammans fix broken relative links [#5415 state:committed]
tilsammans authored
41 # See the mapping rules in table_name and the full example in link:files/activerecord/README_rdoc.html for more insight.
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
42 #
db045db @dhh Initial
dhh authored
43 # == Creation
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
44 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
45 # Active Records accept constructor parameters either in a hash or as a block. The hash
46 # method is especially useful when you're receiving the data from somewhere else, like an
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
47 # HTTP request. It works like this:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
48 #
0591c53 @dhh Made the dynamic finders use the new find API and updated the example…
dhh authored
49 # user = User.new(:name => "David", :occupation => "Code Artist")
db045db @dhh Initial
dhh authored
50 # user.name # => "David"
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
51 #
db045db @dhh Initial
dhh authored
52 # You can also use block initialization:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
53 #
db045db @dhh Initial
dhh authored
54 # user = User.new do |u|
55 # u.name = "David"
56 # u.occupation = "Code Artist"
57 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
58 #
db045db @dhh Initial
dhh authored
59 # And of course you can just create a bare object and specify the attributes after the fact:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
60 #
db045db @dhh Initial
dhh authored
61 # user = User.new
62 # user.name = "David"
63 # user.occupation = "Code Artist"
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
64 #
db045db @dhh Initial
dhh authored
65 # == Conditions
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
66 #
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored
67 # Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement.
9e18380 @fxn Revert "Explicitly included hashes in sentence regarding SQL-injectio…
fxn authored
68 # The array form is to be used when the condition input is tainted and requires sanitization. The string form can
69 # be used for statements that don't involve tainted data. The hash form works much like the array form, except
70 # only equality and range is possible. Examples:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
71 #
48052d7 @jeremy to_xml fixes, features, and speedup. Closes #4989.
jeremy authored
72 # class User < ActiveRecord::Base
db045db @dhh Initial
dhh authored
73 # def self.authenticate_unsafely(user_name, password)
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
74 # where("user_name = '#{user_name}' AND password = '#{password}'").first
db045db @dhh Initial
dhh authored
75 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
76 #
db045db @dhh Initial
dhh authored
77 # def self.authenticate_safely(user_name, password)
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
78 # where("user_name = ? AND password = ?", user_name, password).first
db045db @dhh Initial
dhh authored
79 # end
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored
80 #
81 # def self.authenticate_safely_simply(user_name, password)
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
82 # where(:user_name => user_name, :password => password).first
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored
83 # end
db045db @dhh Initial
dhh authored
84 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
85 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
86 # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query
87 # and is thus susceptible to SQL-injection attacks if the <tt>user_name</tt> and +password+
04d37b0 @smartinez87 Remove extra whitespaces
smartinez87 authored
88 # parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
89 # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+
90 # before inserting them in the query, which will ensure that an attacker can't escape the
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
91 # query and fake the login (or worse).
2575b3b @dhh Added extra words of caution for guarding against SQL-injection attacks
dhh authored
92 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
93 # When using multiple parameters in the conditions, it can easily become hard to read exactly
94 # what the fourth or fifth question mark is supposed to represent. In those cases, you can
95 # resort to named bind variables instead. That's done by replacing the question marks with
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
96 # symbols and supplying a hash with values for the matching symbol keys:
5cd38ca @dhh Added documentation about named bind variables
dhh authored
97 #
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
98 # Company.where(
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
99 # "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
5cd38ca @dhh Added documentation about named bind variables
dhh authored
100 # { :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' }
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
101 # ).first
5cd38ca @dhh Added documentation about named bind variables
dhh authored
102 #
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored
103 # Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
104 # operator. For instance:
105 #
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
106 # Student.where(:first_name => "Harvey", :status => 1)
107 # Student.where(params[:student])
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored
108 #
2876707 @jeremy Pass a range in :conditions to use the SQL BETWEEN operator. Closes #…
jeremy authored
109 # A range may be used in the hash to use the SQL BETWEEN operator:
110 #
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
111 # Student.where(:grade => 9..12)
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored
112 #
aa4af60 @lifo Improve documentation.
lifo authored
113 # An array may be used in the hash to use the SQL IN operator:
114 #
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
115 # Student.where(:grade => [9,11,12])
aa4af60 @lifo Improve documentation.
lifo authored
116 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
117 # When joining tables, nested hashes or keys written in the form 'table_name.column_name'
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
118 # can be used to qualify the table name of a particular condition. For instance:
e033b5d @lifo Merge docrails
lifo authored
119 #
e552fe1 change activerecord query conditions example to avoid 'type' as colum…
Steve Bourne authored
120 # Student.joins(:schools).where(:schools => { :category => 'public' })
121 # Student.joins(:schools).where('schools.category' => 'public' )
e033b5d @lifo Merge docrails
lifo authored
122 #
db045db @dhh Initial
dhh authored
123 # == Overwriting default accessors
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
124 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
125 # All column values are automatically available through basic accessors on the Active Record
126 # object, but sometimes you want to specialize this behavior. This can be done by overwriting
127 # the default accessors (using the same name as the attribute) and calling
128 # <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
129 # change things.
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
130 #
db045db @dhh Initial
dhh authored
131 # class Song < ActiveRecord::Base
132 # # Uses an integer of seconds to hold the length of the song
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
133 #
db045db @dhh Initial
dhh authored
134 # def length=(minutes)
64092de @fxn Improve documentation coverage and markup
fxn authored
135 # write_attribute(:length, minutes.to_i * 60)
db045db @dhh Initial
dhh authored
136 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
137 #
db045db @dhh Initial
dhh authored
138 # def length
0591c53 @dhh Made the dynamic finders use the new find API and updated the example…
dhh authored
139 # read_attribute(:length) / 60
db045db @dhh Initial
dhh authored
140 # end
141 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
142 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
143 # You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt>
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
144 # instead of <tt>write_attribute(:attribute, value)</tt> and <tt>read_attribute(:attribute)</tt>.
0591c53 @dhh Made the dynamic finders use the new find API and updated the example…
dhh authored
145 #
e4d845e Document automatically generated predicate methods for attributes. Cl…
Marcel Molina authored
146 # == Attribute query methods
147 #
148 # In addition to the basic accessors, query methods are also automatically available on the Active Record object.
149 # Query methods allow you to test whether an attribute value is present.
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
150 #
e4d845e Document automatically generated predicate methods for attributes. Cl…
Marcel Molina authored
151 # For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
152 # to determine whether the user has a name:
153 #
154 # user = User.new(:name => "David")
155 # user.name? # => true
156 #
157 # anonymous = User.new(:name => "")
158 # anonymous.name? # => false
159 #
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
160 # == Accessing attributes before they have been typecasted
4eab375 @dhh Finished polishing API docs
dhh authored
161 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
162 # Sometimes you want to be able to read the raw attribute data without having the column-determined
163 # typecast run its course first. That can be done by using the <tt><attribute>_before_type_cast</tt>
164 # accessors that all attributes have. For example, if your Account model has a <tt>balance</tt> attribute,
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
165 # you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>.
4eab375 @dhh Finished polishing API docs
dhh authored
166 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
167 # This is especially useful in validation situations where the user might supply a string for an
168 # integer field and you want to display the original string back in an error message. Accessing the
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
169 # attribute normally would typecast the string to 0, which isn't what you want.
4eab375 @dhh Finished polishing API docs
dhh authored
170 #
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting obj…
dhh authored
171 # == Dynamic attribute-based finders
172 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
173 # Dynamic attribute-based finders are a cleaner way of getting (and/or creating) objects
174 # by simple queries without turning to SQL. They work by appending the name of an attribute
175 # to <tt>find_by_</tt>, <tt>find_last_by_</tt>, or <tt>find_all_by_</tt> and thus produces finders
176 # like <tt>Person.find_by_user_name</tt>, <tt>Person.find_all_by_last_name</tt>, and
177 # <tt>Payment.find_by_transaction_id</tt>. Instead of writing
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
178 # <tt>Person.where(:user_name => user_name).first</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
179 # And instead of writing <tt>Person.where(:last_name => last_name).all</tt>, you just do
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
180 # <tt>Person.find_all_by_last_name(last_name)</tt>.
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
181 #
56efdbc Document exclamation point on dynamic finders
Florent Guilleux authored
182 # It's possible to add an exclamation point (!) on the end of the dynamic finders to get them to raise an
0d5a6f6 @jonleighton In 1efd882, ConnectionAdapters was put under eager_autoload. Due to t…
jonleighton authored
183 # <tt>ActiveRecord::RecordNotFound</tt> error if they do not return any records,
56efdbc Document exclamation point on dynamic finders
Florent Guilleux authored
184 # like <tt>Person.find_by_last_name!</tt>.
185 #
d3eacf9 @neerajdotname Adding to AR::Base documentation about dynamically scopeded_by query
neerajdotname authored
186 # It's also possible to use multiple attributes in the same find by separating them with "_and_".
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
187 #
d3eacf9 @neerajdotname Adding to AR::Base documentation about dynamically scopeded_by query
neerajdotname authored
188 # Person.where(:user_name => user_name, :password => password).first
2acb5e3 @fxn removes unrealistic example (authentication plus gender?), that it is…
fxn authored
189 # Person.find_by_user_name_and_password(user_name, password) # with dynamic finder
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
190 #
d3eacf9 @neerajdotname Adding to AR::Base documentation about dynamically scopeded_by query
neerajdotname authored
191 # It's even possible to call these dynamic finder methods on relations and named scopes.
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
192 #
193 # Payment.order("created_on").find_all_by_amount(50)
194 # Payment.pending.find_last_by_amount(100)
959f362 @dhh Added find_all style to the new dynamic finders
dhh authored
195 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
196 # The same dynamic finder style can be used to create the object if it doesn't already exist.
197 # This dynamic finder is called with <tt>find_or_create_by_</tt> and will return the object if
198 # it already exists and otherwise creates it, then returns it. Protected attributes won't be set
199 # unless they are given in a block.
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many …
dhh authored
200 #
201 # # No 'Summer' tag exists
202 # Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
203 #
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many …
dhh authored
204 # # Now the 'Summer' tag does exist
205 # Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
206 #
c10b225 @dhh Fixed that ActiveRecord#Base.find_or_create/initialize would not hono…
dhh authored
207 # # Now 'Bob' exist and is an 'admin'
208 # User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }
209 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
210 # Use the <tt>find_or_initialize_by_</tt> finder if you want to return a new record without
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
211 # saving it first. Protected attributes won't be set unless they are given in a block.
d19e464 @sstephenson Added find_or_initialize_by_X which works like find_or_create_by_X bu…
sstephenson authored
212 #
213 # # No 'Winter' tag exists
214 # winter = Tag.find_or_initialize_by_name("Winter")
1f06652 @dchelimsky use persisted? instead of new_record? wherever possible
dchelimsky authored
215 # winter.persisted? # false
d19e464 @sstephenson Added find_or_initialize_by_X which works like find_or_create_by_X bu…
sstephenson authored
216 #
14cc8d2 @jeremy find_or_create_by_* takes a hash so you can create with more attribut…
jeremy authored
217 # To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
218 # a list of parameters.
14cc8d2 @jeremy find_or_create_by_* takes a hash so you can create with more attribut…
jeremy authored
219 #
220 # Tag.find_or_create_by_name(:name => "rails", :creator => current_user)
221 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
222 # That will either find an existing tag named "rails", or create a new one while setting the
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
223 # user that created it.
14cc8d2 @jeremy find_or_create_by_* takes a hash so you can create with more attribut…
jeremy authored
224 #
d3eacf9 @neerajdotname Adding to AR::Base documentation about dynamically scopeded_by query
neerajdotname authored
225 # Just like <tt>find_by_*</tt>, you can also use <tt>scoped_by_*</tt> to retrieve data. The good thing about
226 # using this feature is that the very first time result is returned using <tt>method_missing</tt> technique
227 # but after that the method is declared on the class. Henceforth <tt>method_missing</tt> will not be hit.
228 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
229 # User.scoped_by_user_name('David')
d3eacf9 @neerajdotname Adding to AR::Base documentation about dynamically scopeded_by query
neerajdotname authored
230 #
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
231 # == Saving arrays, hashes, and other non-mappable objects in text columns
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
232 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
233 # Active Record can serialize any object in text columns using YAML. To do so, you must
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
234 # specify this with a call to the class method +serialize+.
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
235 # This makes it possible to store arrays, hashes, and other non-mappable objects without doing
236 # any additional work.
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
237 #
db045db @dhh Initial
dhh authored
238 # class User < ActiveRecord::Base
239 # serialize :preferences
240 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
241 #
ca2eb16 Fix syntax error in documentation. Closes #4679. [mislav@nippur.irb.hr]
Marcel Molina authored
242 # user = User.create(:preferences => { "background" => "black", "display" => large })
db045db @dhh Initial
dhh authored
243 # User.find(user.id).preferences # => { "background" => "black", "display" => large }
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
244 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
245 # You can also specify a class option as the second parameter that'll raise an exception
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
246 # if a serialized object is retrieved as a descendant of a class not in the hierarchy.
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
247 #
db045db @dhh Initial
dhh authored
248 # class User < ActiveRecord::Base
66f44e6 @dhh Updated documentation for serialize
dhh authored
249 # serialize :preferences, Hash
db045db @dhh Initial
dhh authored
250 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
251 #
0591c53 @dhh Made the dynamic finders use the new find API and updated the example…
dhh authored
252 # user = User.create(:preferences => %w( one two three ))
db045db @dhh Initial
dhh authored
253 # User.find(user.id).preferences # raises SerializationTypeMismatch
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
254 #
351331f @guillermo Make serialized columns with explicit object_type return a new instan…
guillermo authored
255 # When you specify a class option, the default value for that attribute will be a new
256 # instance of that class.
257 #
258 # class User < ActiveRecord::Base
259 # serialize :preferences, OpenStruct
260 # end
261 #
262 # user = User.new
263 # user.preferences.theme_color = "red"
264 #
265 #
db045db @dhh Initial
dhh authored
266 # == Single table inheritance
267 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
268 # Active Record allows inheritance by storing the name of the class in a column that by
269 # default is named "type" (can be changed by overwriting <tt>Base.inheritance_column</tt>).
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
270 # This means that an inheritance looking like this:
db045db @dhh Initial
dhh authored
271 #
272 # class Company < ActiveRecord::Base; end
273 # class Firm < Company; end
274 # class Client < Company; end
275 # class PriorityClient < Client; end
276 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
277 # When you do <tt>Firm.create(:name => "37signals")</tt>, this record will be saved in
278 # the companies table with type = "Firm". You can then fetch this row again using
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
279 # <tt>Company.where(:name => '37signals').first</tt> and it will return a Firm object.
db045db @dhh Initial
dhh authored
280 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
281 # If you don't have a type column defined in your table, single-table inheritance won't
282 # be triggered. In that case, it'll work just like normal subclasses with no special magic
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
283 # for differentiating between them or reloading the right type with find.
f033833 @dhh Improving documentation...
dhh authored
284 #
db045db @dhh Initial
dhh authored
285 # Note, all the attributes for all the cases are kept in the same table. Read more:
286 # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
287 #
db045db @dhh Initial
dhh authored
288 # == Connection to multiple databases in different models
289 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
290 # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved
291 # by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this
292 # connection. But you can also set a class-specific connection. For example, if Course is an
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
293 # ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
98dc582 @lifo Merge docrails.
lifo authored
294 # and Course and all of its subclasses will use this connection instead.
db045db @dhh Initial
dhh authored
295 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
296 # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is
297 # a Hash indexed by the class. If a connection is requested, the retrieve_connection method
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
298 # will go up the class-hierarchy until a connection is found in the connection pool.
db045db @dhh Initial
dhh authored
299 #
300 # == Exceptions
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
301 #
dc4eec1 @lifo Merge docrails:
lifo authored
302 # * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record.
303 # * AdapterNotSpecified - The configuration hash used in <tt>establish_connection</tt> didn't include an
db045db @dhh Initial
dhh authored
304 # <tt>:adapter</tt> key.
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
305 # * AdapterNotFound - The <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
306 # non-existent adapter
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
307 # (or a bad spelling of an existing one).
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
308 # * AssociationTypeMismatch - The object assigned to the association wasn't of the type
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
309 # specified in the association definition.
dc4eec1 @lifo Merge docrails:
lifo authored
310 # * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
311 # * ConnectionNotEstablished+ - No connection has been established. Use <tt>establish_connection</tt>
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
312 # before querying.
dc4eec1 @lifo Merge docrails:
lifo authored
313 # * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
314 # or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
315 # nothing was found, please check its documentation for further details.
316 # * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
317 # * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
318 # <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
319 # AttributeAssignmentError
d2fefbe @dhh Added MultiparameterAssignmentErrors and AttributeAssignmentError exc…
dhh authored
320 # objects that should be inspected to determine which attributes triggered the errors.
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
321 # * AttributeAssignmentError - An error occurred while doing a mass assignment through the
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
322 # <tt>attributes=</tt> method.
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
323 # You can inspect the +attribute+ property of the exception object to determine which attribute
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
324 # triggered the error.
5707027 @dhh Added better exception error when unknown column types are used with …
dhh authored
325 #
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
326 # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
dc4eec1 @lifo Merge docrails:
lifo authored
327 # So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all
db045db @dhh Initial
dhh authored
328 # instances in the current object space.
329 class Base
0905396 @miloops construct_finder_sql now use Arel
miloops authored
330 ##
dbbae5e @lifo Merge with docrails
lifo authored
331 # :singleton-method:
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
332 # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class,
333 # which is then passed on to any new database connections made and which can be retrieved on both
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
334 # a class and instance level by calling +logger+.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7401
technoweenie authored
335 cattr_accessor :logger, :instance_writer => false
e694114 @jeremy Deprecation: removed Reloadable.
jeremy authored
336
dbbae5e @lifo Merge with docrails
lifo authored
337 ##
338 # :singleton-method:
a293278 @lifo Merge docrails
lifo authored
339 # Contains the database configuration - as is typically stored in config/database.yml -
340 # as a Hash.
341 #
342 # For example, the following database.yml...
0905396 @miloops construct_finder_sql now use Arel
miloops authored
343 #
a293278 @lifo Merge docrails
lifo authored
344 # development:
345 # adapter: sqlite3
346 # database: db/development.sqlite3
0905396 @miloops construct_finder_sql now use Arel
miloops authored
347 #
a293278 @lifo Merge docrails
lifo authored
348 # production:
349 # adapter: sqlite3
350 # database: db/production.sqlite3
351 #
352 # ...would result in ActiveRecord::Base.configurations to look like this:
353 #
354 # {
355 # 'development' => {
356 # 'adapter' => 'sqlite3',
357 # 'database' => 'db/development.sqlite3'
358 # },
359 # 'production' => {
360 # 'adapter' => 'sqlite3',
361 # 'database' => 'db/production.sqlite3'
362 # }
363 # }
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7401
technoweenie authored
364 cattr_accessor :configurations, :instance_writer => false
c4a3634 @jeremy Corrected @@configurations typo. #1410 [david@ruppconsulting.com]
jeremy authored
365 @@configurations = {}
366
dbbae5e @lifo Merge with docrails
lifo authored
367 ##
368 # :singleton-method:
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
369 # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
370 # dates and times from the database. This is set to :local by default.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7401
technoweenie authored
371 cattr_accessor :default_timezone, :instance_writer => false
60de8c1 @dhh Added Base.default_timezone accessor that determines whether to use T…
dhh authored
372 @@default_timezone = :local
d8641ca @jeremy CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. M…
jeremy authored
373
dbbae5e @lifo Merge with docrails
lifo authored
374 ##
375 # :singleton-method:
24c3599 @sstephenson Support using different database adapters for development and test wi…
sstephenson authored
376 # Specifies the format to use when dumping the database schema with Rails'
04d37b0 @smartinez87 Remove extra whitespaces
smartinez87 authored
377 # Rakefile. If :sql, the schema is dumped as (potentially database-
378 # specific) SQL statements. If :ruby, the schema is dumped as an
24c3599 @sstephenson Support using different database adapters for development and test wi…
sstephenson authored
379 # ActiveRecord::Schema file which can be loaded into any database that
04d37b0 @smartinez87 Remove extra whitespaces
smartinez87 authored
380 # supports migrations. Use :ruby if you want to have different database
24c3599 @sstephenson Support using different database adapters for development and test wi…
sstephenson authored
381 # adapters for, e.g., your development and test environments.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7401
technoweenie authored
382 cattr_accessor :schema_format , :instance_writer => false
660952e @dhh CHANGED DEFAULT: ActiveRecord::Base.schema_format is now :ruby by def…
dhh authored
383 @@schema_format = :ruby
3b0e1d9 @josh Prefer string core_ext inflector methods over directly accessing Infl…
josh authored
384
dbbae5e @lifo Merge with docrails
lifo authored
385 ##
386 # :singleton-method:
155f0be @rizwanreza Changes migration number to version due to ambiguity. [#3065 state:co…
rizwanreza authored
387 # Specify whether or not to use timestamps for migration versions
bbab639 @nikz Set config.active_record.timestamped_migrations = false to have migra…
nikz authored
388 cattr_accessor :timestamped_migrations , :instance_writer => false
389 @@timestamped_migrations = true
390
db045db @dhh Initial
dhh authored
391 class << self # Class methods
61bcc31 @joshsusser use GeneratedFeatureMethods module for associations
joshsusser authored
392 def inherited(child_class) #:nodoc:
393 # force attribute methods to be higher in inheritance hierarchy than other generated methods
394 child_class.generated_attribute_methods
395 child_class.generated_feature_methods
396 super
397 end
398
399 def generated_feature_methods
3da5fba @jonleighton Fix ruby 1.8 compat. const_defined? only takes a second arg on 1.9.
jonleighton authored
400 @generated_feature_methods ||= begin
401 mod = const_set(:GeneratedFeatureMethods, Module.new)
402 include mod
403 mod
61bcc31 @joshsusser use GeneratedFeatureMethods module for associations
joshsusser authored
404 end
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
405 end
fd40fbc @jeremy Generate less garbage when expanding range bind variables in conditions
jeremy authored
406
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
407 # Returns a string like 'Post(id:integer, title:string, body:text)'
408 def inspect
409 if self == Base
410 super
411 elsif abstract_class?
412 "#{super}(abstract)"
413 elsif table_exists?
414 attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', '
415 "#{super}(#{attr_list})"
416 else
417 "#{super}(Table doesn't exist)"
418 end
419 end
cd994ef @lifo Allow conditions on multiple tables to be specified using hash.
lifo authored
420
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
421 # Overwrite the default class equality method to provide support for association proxies.
422 def ===(object)
423 object.is_a?(self)
424 end
fd40fbc @jeremy Generate less garbage when expanding range bind variables in conditions
jeremy authored
425
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
426 def arel_table
427 @arel_table ||= Arel::Table.new(table_name, arel_engine)
428 end
2876707 @jeremy Pass a range in :conditions to use the SQL BETWEEN operator. Closes #…
jeremy authored
429
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
430 def arel_engine
431 @arel_engine ||= begin
432 if self == ActiveRecord::Base
433 ActiveRecord::Base
c2ed453 @dhh Fix quote_bound_value to not map Strings #1416 [htonl]
dhh authored
434 else
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
435 connection_handler.connection_pools[name] ? self : superclass.arel_engine
872ddaf @dhh Added bind-named arrays for interpolating a group of ids or strings i…
dhh authored
436 end
437 end
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
438 end
872ddaf @dhh Added bind-named arrays for interpolating a group of ids or strings i…
dhh authored
439
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
440 private
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
441
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
442 def relation #:nodoc:
443 @relation ||= Relation.new(self, arel_table)
444
445 if finder_needs_type_condition?
446 @relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name)
447 else
448 @relation
aaf9a45 @dhh Added Base.validate_uniqueness thatv alidates whether the value of th…
dhh authored
449 end
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
450 end
db045db @dhh Initial
dhh authored
451 end
452
453 public
454 # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
455 # attributes but not yet saved (pass a hash with key names matching the associated table column names).
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
456 # In both instances, valid attribute keys are determined by the column names of the associated table --
db045db @dhh Initial
dhh authored
457 # hence you can't have attributes that aren't part of the table columns.
7c5ae0a @joshk Added mass-assignment security :as and :without_protection support to…
joshk authored
458 #
459 # +initialize+ respects mass-assignment security and accepts either +:as+ or +:without_protection+ options
460 # in the +options+ parameter.
461 #
462 # ==== Examples
463 # # Instantiates a single new object
464 # User.new(:first_name => 'Jamie')
465 #
b2451f4 @joshk renamed mass-assignment scopes to roles, updated code, tests, docs an…
joshk authored
466 # # Instantiates a single new object using the :admin mass-assignment security role
7c5ae0a @joshk Added mass-assignment security :as and :without_protection support to…
joshk authored
467 # User.new({ :first_name => 'Jamie', :is_admin => true }, :as => :admin)
468 #
469 # # Instantiates a single new object bypassing mass-assignment security
470 # User.new({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true)
471 def initialize(attributes = nil, options = {})
6d30002 @lifo Revert "Refactoring attributes/types" [#3348 state:open]
lifo authored
472 @attributes = attributes_from_column_definition
839f3bf @tenderlove just use a hash for doing association caching
tenderlove authored
473 @association_cache = {}
344a2d5 @tenderlove use a hash for caching aggregations rather than ivars
tenderlove authored
474 @aggregation_cache = {}
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writ…
NZKoz authored
475 @attributes_cache = {}
e444439 @josevalim Partialy revert f1c13b0
josevalim authored
476 @new_record = true
95bd56e @tenderlove speeding up clone_attributes, changing readonly to be initialized in …
tenderlove authored
477 @readonly = false
5de3698 @tenderlove cleaning up many more warnings in activerecord [#4180 state:resolved]
tenderlove authored
478 @destroyed = false
479 @marked_for_destruction = false
8c3e46c @tenderlove clean up more warnings, remove unnecessary methods, fix eval line num…
tenderlove authored
480 @previously_changed = {}
481 @changed_attributes = {}
5ddb60f @tenderlove initialize instance variables
tenderlove authored
482 @relation = nil
5de3698 @tenderlove cleaning up many more warnings in activerecord [#4180 state:resolved]
tenderlove authored
483
db045db @dhh Initial
dhh authored
484 ensure_proper_type
351331f @guillermo Make serialized columns with explicit object_type return a new instan…
guillermo authored
485 set_serialized_attributes
3da29f6 @lifo Remove AR#scope() method
lifo authored
486
cdfd013 @marklazz Set attributes properly for model built from association with conditi…
marklazz authored
487 populate_with_current_scope_attributes
7c5ae0a @joshk Added mass-assignment security :as and :without_protection support to…
joshk authored
488
489 assign_attributes(attributes, options) if attributes
3da29f6 @lifo Remove AR#scope() method
lifo authored
490
26caf32 @tenderlove remove useless assignment
tenderlove authored
491 yield self if block_given?
57bc25c @jfirebaugh Use run_callbacks; the generated _run_<name>_callbacks method is not …
jfirebaugh authored
492 run_callbacks :initialize
db045db @dhh Initial
dhh authored
493 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
494
04d37b0 @smartinez87 Remove extra whitespaces
smartinez87 authored
495 # Initialize an empty model object from +coder+. +coder+ must contain
496 # the attributes necessary for initializing an empty model object. For
505b532 @tenderlove speeding up object instantiation by eliminating instance_eval
tenderlove authored
497 # example:
498 #
499 # class Post < ActiveRecord::Base
500 # end
501 #
502 # post = Post.allocate
503 # post.init_with('attributes' => { 'title' => 'hello world' })
504 # post.title # => 'hello world'
505 def init_with(coder)
506 @attributes = coder['attributes']
5ddb60f @tenderlove initialize instance variables
tenderlove authored
507 @relation = nil
5b42e96 @tenderlove make sure de-serialization happens on object instantiation
tenderlove authored
508
351331f @guillermo Make serialized columns with explicit object_type return a new instan…
guillermo authored
509 set_serialized_attributes
5b42e96 @tenderlove make sure de-serialization happens on object instantiation
tenderlove authored
510
505b532 @tenderlove speeding up object instantiation by eliminating instance_eval
tenderlove authored
511 @attributes_cache, @previously_changed, @changed_attributes = {}, {}, {}
839f3bf @tenderlove just use a hash for doing association caching
tenderlove authored
512 @association_cache = {}
344a2d5 @tenderlove use a hash for caching aggregations rather than ivars
tenderlove authored
513 @aggregation_cache = {}
1f06652 @dchelimsky use persisted? instead of new_record? wherever possible
dchelimsky authored
514 @readonly = @destroyed = @marked_for_destruction = false
e444439 @josevalim Partialy revert f1c13b0
josevalim authored
515 @new_record = false
57bc25c @jfirebaugh Use run_callbacks; the generated _run_<name>_callbacks method is not …
jfirebaugh authored
516 run_callbacks :find
517 run_callbacks :initialize
24485b9 @swistak Separated initialization
swistak authored
518
519 self
505b532 @tenderlove speeding up object instantiation by eliminating instance_eval
tenderlove authored
520 end
521
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
522 # Duped objects have no id assigned and are treated as new records. Note
523 # that this is a "shallow" copy as it copies the object's attributes
524 # only, not its associations. The extent of a "deep" copy is application
525 # specific and is therefore left to the application to implement according
526 # to its need.
527 # The dup method does not preserve the timestamps (created|updated)_(at|on).
528 def initialize_dup(other)
529 cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast)
530 cloned_attributes.delete(self.class.primary_key)
9e4b715 @josevalim Ensure assign_attributes and update_attributes do not fail on nil, cl…
josevalim authored
531
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
532 @attributes = cloned_attributes
a08d04b @joshk Added assign_attributes to Active Record which accepts a mass-assignm…
joshk authored
533
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
534 _run_after_initialize_callbacks if respond_to?(:_run_after_initialize_callbacks)
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
535
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
536 @changed_attributes = {}
537 attributes_from_column_definition.each do |attr, orig_value|
538 @changed_attributes[attr] = orig_value if field_changed?(attr, orig_value, @attributes[attr])
db045db @dhh Initial
dhh authored
539 end
3d0a9ff @dhh Aesthetics, baby
dhh authored
540
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
541 @aggregation_cache = {}
542 @association_cache = {}
543 @attributes_cache = {}
544 @new_record = true
774ff18 @akaspick Allow nested attributes in associations to update values in it's owne…
akaspick authored
545
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
546 ensure_proper_type
547 populate_with_current_scope_attributes
548 super
db045db @dhh Initial
dhh authored
549 end
550
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
551 # Backport dup from 1.9 so that initialize_dup() gets called
552 unless Object.respond_to?(:initialize_dup)
553 def dup # :nodoc:
554 copy = super
555 copy.initialize_dup(self)
556 copy
557 end
bd79a4e @dhh Fixed that clone would break when an aggregate had the same name as o…
dhh authored
558 end
559
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
560 # Populate +coder+ with attributes about this record that should be
561 # serialized. The structure of +coder+ defined in this method is
562 # guaranteed to match the structure of +coder+ passed to the +init_with+
563 # method.
39e1ac6 @lifo Merge docrails
lifo authored
564 #
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
565 # Example:
39e1ac6 @lifo Merge docrails
lifo authored
566 #
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
567 # class Post < ActiveRecord::Base
568 # end
569 # coder = {}
570 # Post.new.encode_with(coder)
571 # coder # => { 'id' => nil, ... }
572 def encode_with(coder)
573 coder['attributes'] = attributes
db045db @dhh Initial
dhh authored
574 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
575
d7db6a8 @joshk class inheritable attributes is used no more! all internal use of cla…
joshk authored
576 # Returns true if +comparison_object+ is the same exact object, or +comparison_object+
a820d0a @fxn revises RDoc of AR::Base#==
fxn authored
577 # is of the same type and +self+ has an ID and it is equal to +comparison_object.id+.
578 #
579 # Note that new records are different from any other record by definition, unless the
580 # other record is the receiver itself. Besides, if you fetch existing records with
581 # +select+ and leave the ID out, you're on your own, this predicate will return false.
582 #
583 # Note also that destroying a record preserves its ID in the model instance, so deleted
584 # models are still comparable.
db045db @dhh Initial
dhh authored
585 def ==(comparison_object)
8e19a5d @tenderlove call super rather than delegating to the other objects equal? method
tenderlove authored
586 super ||
4718d09 @spastorino Models should be equals even after destroyed
spastorino authored
587 comparison_object.instance_of?(self.class) &&
588 id.present? &&
589 comparison_object.id == id
db045db @dhh Initial
dhh authored
590 end
2545da6 @tenderlove just alias eql? to == for frewer method calls
tenderlove authored
591 alias :eql? :==
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
592
db045db @dhh Initial
dhh authored
593 # Delegates to id in order to allow two records of the same type and id to work with something like:
594 # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
595 def hash
cfef86c @dhh Fixed bug in Base#hash method that would treat records with the same …
dhh authored
596 id.hash
db045db @dhh Initial
dhh authored
597 end
598
8c2177c Add documentation for freeze and readonly related methods. Closes #8878
Marcel Molina authored
599 # Freeze the attributes hash such that associations are still accessible, even on destroyed records.
24a9050 @dhh Changed the callbacks such that observers are notified before the in-…
dhh authored
600 def freeze
b1a4f91 @jamis Make destroy return self #1913 [sebastian.kanthak@muehlheim.de]
jamis authored
601 @attributes.freeze; self
24a9050 @dhh Changed the callbacks such that observers are notified before the in-…
dhh authored
602 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
603
8c2177c Add documentation for freeze and readonly related methods. Closes #8878
Marcel Molina authored
604 # Returns +true+ if the attributes hash has been frozen.
24a9050 @dhh Changed the callbacks such that observers are notified before the in-…
dhh authored
605 def frozen?
606 @attributes.frozen?
607 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
608
bc743dc @dmathieu allow comparison on model objects - Closes #1858
dmathieu authored
609 # Allows sort on objects
610 def <=>(other_object)
eb22c51 @dmathieu comparing different classes returns nil
dmathieu authored
611 if other_object.is_a?(self.class)
612 self.to_key <=> other_object.to_key
613 else
614 nil
615 end
bc743dc @dmathieu allow comparison on model objects - Closes #1858
dmathieu authored
616 end
617
8c2177c Add documentation for freeze and readonly related methods. Closes #8878
Marcel Molina authored
618 # Returns +true+ if the record is read only. Records loaded through joins with piggy-back
619 # attributes will be marked as read only since they cannot be saved.
64fcb75 @jeremy r3618@sedna: jeremy | 2005-10-14 12:06:03 -0700
jeremy authored
620 def readonly?
95bd56e @tenderlove speeding up clone_attributes, changing readonly to be initialized in …
tenderlove authored
621 @readonly
64fcb75 @jeremy r3618@sedna: jeremy | 2005-10-14 12:06:03 -0700
jeremy authored
622 end
623
8c2177c Add documentation for freeze and readonly related methods. Closes #8878
Marcel Molina authored
624 # Marks this record as read only.
625 def readonly!
64fcb75 @jeremy r3618@sedna: jeremy | 2005-10-14 12:06:03 -0700
jeremy authored
626 @readonly = true
627 end
d872281 @dhh Fixed to_xml across the board to use nice indention, better skip_attr…
dhh authored
628
8c2177c Add documentation for freeze and readonly related methods. Closes #8878
Marcel Molina authored
629 # Returns the contents of the record as a nicely formatted string.
e48b062 @jeremy Sanitize Base#inspect. Closes #8392.
jeremy authored
630 def inspect
b2db874 @franckverrot Fix the AR::Base#inspect method [closes #1294]
franckverrot authored
631 inspection = if @attributes
632 self.class.column_names.collect { |name|
633 if has_attribute?(name)
634 "#{name}: #{attribute_for_inspect(name)}"
635 end
636 }.compact.join(", ")
637 else
638 "not initialized"
639 end
640 "#<#{self.class} #{inspection}>"
e48b062 @jeremy Sanitize Base#inspect. Closes #8392.
jeremy authored
641 end
64fcb75 @jeremy r3618@sedna: jeremy | 2005-10-14 12:06:03 -0700
jeremy authored
642
52eedf5 @jonleighton Add hackery to make Syck use encode_with/init_with. Fixes 1.8 after r…
jonleighton authored
643 # Hackery to accomodate Syck. Remove for 4.0.
644 def to_yaml(opts = {}) #:nodoc:
645 if YAML.const_defined?(:ENGINE) && !YAML::ENGINE.syck?
646 super
647 else
648 coder = {}
649 encode_with(coder)
650 YAML.quick_emit(self, opts) do |out|
651 out.map(taguri, to_yaml_style) do |map|
652 coder.each { |k, v| map.add(k, v) }
653 end
654 end
655 end
656 end
657
658 # Hackery to accomodate Syck. Remove for 4.0.
659 def yaml_initialize(tag, coder) #:nodoc:
660 init_with(coder)
661 end
662
db045db @dhh Initial
dhh authored
663 private
664
e9fa602 @jonleighton Define to_ary on ActiveRecord::Base to return nil. Improve performanc…
jonleighton authored
665 # Under Ruby 1.9, Array#flatten will call #to_ary (recursively) on each of the elements
666 # of the array, and then rescues from the possible NoMethodError. If those elements are
667 # ActiveRecord::Base's, then this triggers the various method_missing's that we have,
668 # which significantly impacts upon performance.
669 #
670 # So we can avoid the method_missing hit by explicitly defining #to_ary as nil here.
671 #
672 # See also http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary/
673 def to_ary # :nodoc:
674 nil
675 end
676
d916c62 @wycats eliminate alias_method_chain from ActiveRecord
wycats authored
677 include ActiveRecord::Persistence
1c4d28b @josh Move model naming into ActiveModel
josh authored
678 extend ActiveModel::Naming
aa002c0 @josh ActiveRecord::QueryCache middleware
josh authored
679 extend QueryCache::ClassMethods
a15e02d @josevalim Unify benchmark APIs.
josevalim authored
680 extend ActiveSupport::Benchmarkable
033e0a0 @josevalim ActiveRecord and ActionPack now use the new descendants implementation.
josevalim authored
681 extend ActiveSupport::DescendantsTracker
a15e02d @josevalim Unify benchmark APIs.
josevalim authored
682
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
683 extend Querying
684 include ReadonlyAttributes
685 include ModelSchema
686 extend Translation
687 include Inheritance
688 include Scoping
689 include DefaultScope
690 extend DynamicMatchers
691 include Sanitization
692 include Integration
693 include AttributeAssignment
56bed51 @josevalim Fix dom_id for ActiveRecord [#4296 state:resolved]
josevalim authored
694 include ActiveModel::Conversion
7254d23 @josh Autoload ActiveRecord files
josh authored
695 include Validations
d916c62 @wycats eliminate alias_method_chain from ActiveRecord
wycats authored
696 extend CounterCache
7254d23 @josh Autoload ActiveRecord files
josh authored
697 include Locking::Optimistic, Locking::Pessimistic
698 include AttributeMethods
c2b075b @josh Concernify AR AttributeMethods
josh authored
699 include AttributeMethods::Read, AttributeMethods::Write, AttributeMethods::BeforeTypeCast, AttributeMethods::Query
62fd1d3 @josh Start separating primary key concerns
josh authored
700 include AttributeMethods::PrimaryKey
c2b075b @josh Concernify AR AttributeMethods
josh authored
701 include AttributeMethods::TimeZoneConversion
702 include AttributeMethods::Dirty
f4853dc @jonleighton Extract attribute serialization code into a separate module
jonleighton authored
703 include AttributeMethods::Serialization
3a40d38 @jonleighton Get rid of the underscore versions of attribute methods!
jonleighton authored
704 include AttributeMethods::DeprecatedUnderscoreRead
4d70359 @josh Integrate ActiveModel::Observing into ActiveRecord
josh authored
705 include Callbacks, ActiveModel::Observing, Timestamp
d90b4e2 @jonleighton Rewrote AssociationPreload.
jonleighton authored
706 include Associations, NamedScope
ce66bfd @swistak IdentityMap - misc fixes
swistak authored
707 include IdentityMap
bcf4e4f @dhh Added ActiveRecord::Base#has_secure_password (via ActiveModel::Secure…
dhh authored
708 include ActiveModel::SecurePassword
ceb33f8 @jonleighton Split out most of the AR::Base code into separate modules :cake:
jonleighton authored
709 include Explain
ec8f045 @alloy Add support for nested object forms to ActiveRecord and the helpers i…
alloy authored
710
711 # AutosaveAssociation needs to be included before Transactions, because we want
712 # #save_with_autosave_associations to be wrapped inside a transaction.
713 include AutosaveAssociation, NestedAttributes
85b64f9 @dhh Added ActiveRecord::Base.store for declaring simple single-column key…
dhh authored
714 include Aggregations, Transactions, Reflection, Serialization, Store
f936a1f @eac Refactoring attributes/types [#3348 state:resolved]
eac authored
715
21eadc1 @spastorino Base#[] and Base#[]= are aliases so implement them as aliases :)
spastorino authored
716 # Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
717 # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
718 # (Alias for the protected read_attribute method).
719 alias [] read_attribute
720
721 # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
722 # (Alias for the protected write_attribute method).
723 alias []= write_attribute
724
725 public :[], :[]=
7254d23 @josh Autoload ActiveRecord files
josh authored
726 end
15aa6e0 @jeremy r4644@asus: jeremy | 2006-06-16 14:57:03 -0700
jeremy authored
727 end
d6b923a @josh get activerecord tests passing with lazy loading
josh authored
728
0d5a6f6 @jonleighton In 1efd882, ConnectionAdapters was put under eager_autoload. Due to t…
jonleighton authored
729 require 'active_record/connection_adapters/abstract/connection_specification'
4aded43 @wycats Replace the placeholder base_hook API with on_load. To specify some c…
wycats authored
730 ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)
Something went wrong with that request. Please try again.