Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 2219 lines (2000 sloc) 92.406 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'
db045db @dhh Initial
dhh authored
30
31 module ActiveRecord #:nodoc:
606088d @eac Mass assignment security refactoring
eac authored
32 # = Active Record
4ad6103 @rizwanreza Adds title and basic description where needed.
rizwanreza authored
33 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
34 # Active Record objects don't specify their attributes directly, but rather infer them from
35 # the table definition with which they're linked. Adding, removing, and changing attributes
36 # 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
37 # 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
38 # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
39 #
20333be @tilsammans fix broken relative links [#5415 state:committed]
tilsammans authored
40 # 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
41 #
db045db @dhh Initial
dhh authored
42 # == Creation
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
43 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
44 # Active Records accept constructor parameters either in a hash or as a block. The hash
45 # 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
46 # HTTP request. It works like this:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
47 #
0591c53 @dhh Made the dynamic finders use the new find API and updated the example…
dhh authored
48 # user = User.new(:name => "David", :occupation => "Code Artist")
db045db @dhh Initial
dhh authored
49 # user.name # => "David"
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
50 #
db045db @dhh Initial
dhh authored
51 # You can also use block initialization:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
52 #
db045db @dhh Initial
dhh authored
53 # user = User.new do |u|
54 # u.name = "David"
55 # u.occupation = "Code Artist"
56 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
57 #
db045db @dhh Initial
dhh authored
58 # 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
59 #
db045db @dhh Initial
dhh authored
60 # user = User.new
61 # user.name = "David"
62 # user.occupation = "Code Artist"
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
63 #
db045db @dhh Initial
dhh authored
64 # == Conditions
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
65 #
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored
66 # 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
67 # The array form is to be used when the condition input is tainted and requires sanitization. The string form can
68 # be used for statements that don't involve tainted data. The hash form works much like the array form, except
69 # only equality and range is possible. Examples:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
70 #
48052d7 @jeremy to_xml fixes, features, and speedup. Closes #4989.
jeremy authored
71 # class User < ActiveRecord::Base
db045db @dhh Initial
dhh authored
72 # def self.authenticate_unsafely(user_name, password)
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
73 # where("user_name = '#{user_name}' AND password = '#{password}'").first
db045db @dhh Initial
dhh authored
74 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
75 #
db045db @dhh Initial
dhh authored
76 # def self.authenticate_safely(user_name, password)
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
77 # where("user_name = ? AND password = ?", user_name, password).first
db045db @dhh Initial
dhh authored
78 # end
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored
79 #
80 # def self.authenticate_safely_simply(user_name, password)
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
81 # 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
82 # end
db045db @dhh Initial
dhh authored
83 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
84 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
85 # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query
86 # and is thus susceptible to SQL-injection attacks if the <tt>user_name</tt> and +password+
04d37b0 @smartinez87 Remove extra whitespaces
smartinez87 authored
87 # 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
88 # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+
89 # 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
90 # query and fake the login (or worse).
2575b3b @dhh Added extra words of caution for guarding against SQL-injection attacks
dhh authored
91 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
92 # When using multiple parameters in the conditions, it can easily become hard to read exactly
93 # what the fourth or fifth question mark is supposed to represent. In those cases, you can
94 # 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
95 # symbols and supplying a hash with values for the matching symbol keys:
5cd38ca @dhh Added documentation about named bind variables
dhh authored
96 #
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
97 # Company.where(
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
98 # "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
5cd38ca @dhh Added documentation about named bind variables
dhh authored
99 # { :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' }
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
100 # ).first
5cd38ca @dhh Added documentation about named bind variables
dhh authored
101 #
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored
102 # Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
103 # operator. For instance:
104 #
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
105 # Student.where(:first_name => "Harvey", :status => 1)
106 # Student.where(params[:student])
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored
107 #
2876707 @jeremy Pass a range in :conditions to use the SQL BETWEEN operator. Closes #…
jeremy authored
108 # A range may be used in the hash to use the SQL BETWEEN operator:
109 #
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
110 # Student.where(:grade => 9..12)
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored
111 #
aa4af60 @lifo Improve documentation.
lifo authored
112 # An array may be used in the hash to use the SQL IN operator:
113 #
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
114 # Student.where(:grade => [9,11,12])
aa4af60 @lifo Improve documentation.
lifo authored
115 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
116 # 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
117 # can be used to qualify the table name of a particular condition. For instance:
e033b5d @lifo Merge docrails
lifo authored
118 #
e552fe1 change activerecord query conditions example to avoid 'type' as colum…
Steve Bourne authored
119 # Student.joins(:schools).where(:schools => { :category => 'public' })
120 # Student.joins(:schools).where('schools.category' => 'public' )
e033b5d @lifo Merge docrails
lifo authored
121 #
db045db @dhh Initial
dhh authored
122 # == Overwriting default accessors
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
123 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
124 # All column values are automatically available through basic accessors on the Active Record
125 # object, but sometimes you want to specialize this behavior. This can be done by overwriting
126 # the default accessors (using the same name as the attribute) and calling
127 # <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
128 # change things.
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
129 #
db045db @dhh Initial
dhh authored
130 # class Song < ActiveRecord::Base
131 # # 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
132 #
db045db @dhh Initial
dhh authored
133 # def length=(minutes)
64092de @fxn Improve documentation coverage and markup
fxn authored
134 # write_attribute(:length, minutes.to_i * 60)
db045db @dhh Initial
dhh authored
135 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
136 #
db045db @dhh Initial
dhh authored
137 # def length
0591c53 @dhh Made the dynamic finders use the new find API and updated the example…
dhh authored
138 # read_attribute(:length) / 60
db045db @dhh Initial
dhh authored
139 # end
140 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
141 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
142 # 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
143 # 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
144 #
e4d845e Document automatically generated predicate methods for attributes. Cl…
Marcel Molina authored
145 # == Attribute query methods
146 #
147 # In addition to the basic accessors, query methods are also automatically available on the Active Record object.
148 # Query methods allow you to test whether an attribute value is present.
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
149 #
e4d845e Document automatically generated predicate methods for attributes. Cl…
Marcel Molina authored
150 # For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
151 # to determine whether the user has a name:
152 #
153 # user = User.new(:name => "David")
154 # user.name? # => true
155 #
156 # anonymous = User.new(:name => "")
157 # anonymous.name? # => false
158 #
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
159 # == Accessing attributes before they have been typecasted
4eab375 @dhh Finished polishing API docs
dhh authored
160 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
161 # Sometimes you want to be able to read the raw attribute data without having the column-determined
162 # typecast run its course first. That can be done by using the <tt><attribute>_before_type_cast</tt>
163 # 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
164 # 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
165 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
166 # This is especially useful in validation situations where the user might supply a string for an
167 # 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
168 # attribute normally would typecast the string to 0, which isn't what you want.
4eab375 @dhh Finished polishing API docs
dhh authored
169 #
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting obj…
dhh authored
170 # == Dynamic attribute-based finders
171 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
172 # Dynamic attribute-based finders are a cleaner way of getting (and/or creating) objects
173 # by simple queries without turning to SQL. They work by appending the name of an attribute
174 # to <tt>find_by_</tt>, <tt>find_last_by_</tt>, or <tt>find_all_by_</tt> and thus produces finders
175 # like <tt>Person.find_by_user_name</tt>, <tt>Person.find_all_by_last_name</tt>, and
176 # <tt>Payment.find_by_transaction_id</tt>. Instead of writing
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
177 # <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
178 # 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
179 # <tt>Person.find_all_by_last_name(last_name)</tt>.
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
180 #
56efdbc Document exclamation point on dynamic finders
Florent Guilleux authored
181 # It's possible to add an exclamation point (!) on the end of the dynamic finders to get them to raise an
0d5a6f6 @jonleighton In 1efd88283ef68d912df215125951a87526768a51, ConnectionAdapters was p…
jonleighton authored
182 # <tt>ActiveRecord::RecordNotFound</tt> error if they do not return any records,
56efdbc Document exclamation point on dynamic finders
Florent Guilleux authored
183 # like <tt>Person.find_by_last_name!</tt>.
184 #
d3eacf9 @neerajdotname Adding to AR::Base documentation about dynamically scopeded_by query
neerajdotname authored
185 # 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
186 #
d3eacf9 @neerajdotname Adding to AR::Base documentation about dynamically scopeded_by query
neerajdotname authored
187 # Person.where(:user_name => user_name, :password => password).first
2acb5e3 @fxn removes unrealistic example (authentication plus gender?), that it is…
fxn authored
188 # 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
189 #
d3eacf9 @neerajdotname Adding to AR::Base documentation about dynamically scopeded_by query
neerajdotname authored
190 # 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
191 #
192 # Payment.order("created_on").find_all_by_amount(50)
193 # Payment.pending.find_last_by_amount(100)
959f362 @dhh Added find_all style to the new dynamic finders
dhh authored
194 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
195 # The same dynamic finder style can be used to create the object if it doesn't already exist.
196 # This dynamic finder is called with <tt>find_or_create_by_</tt> and will return the object if
197 # it already exists and otherwise creates it, then returns it. Protected attributes won't be set
198 # unless they are given in a block.
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many …
dhh authored
199 #
200 # # No 'Summer' tag exists
201 # Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
202 #
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many …
dhh authored
203 # # Now the 'Summer' tag does exist
204 # Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
205 #
c10b225 @dhh Fixed that ActiveRecord#Base.find_or_create/initialize would not hono…
dhh authored
206 # # Now 'Bob' exist and is an 'admin'
207 # User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }
208 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
209 # 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
210 # 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
211 #
212 # # No 'Winter' tag exists
213 # winter = Tag.find_or_initialize_by_name("Winter")
1f06652 @dchelimsky use persisted? instead of new_record? wherever possible
dchelimsky authored
214 # winter.persisted? # false
d19e464 @sstephenson Added find_or_initialize_by_X which works like find_or_create_by_X bu…
sstephenson authored
215 #
14cc8d2 @jeremy find_or_create_by_* takes a hash so you can create with more attribut…
jeremy authored
216 # 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
217 # a list of parameters.
14cc8d2 @jeremy find_or_create_by_* takes a hash so you can create with more attribut…
jeremy authored
218 #
219 # Tag.find_or_create_by_name(:name => "rails", :creator => current_user)
220 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
221 # 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
222 # user that created it.
14cc8d2 @jeremy find_or_create_by_* takes a hash so you can create with more attribut…
jeremy authored
223 #
d3eacf9 @neerajdotname Adding to AR::Base documentation about dynamically scopeded_by query
neerajdotname authored
224 # Just like <tt>find_by_*</tt>, you can also use <tt>scoped_by_*</tt> to retrieve data. The good thing about
225 # using this feature is that the very first time result is returned using <tt>method_missing</tt> technique
226 # but after that the method is declared on the class. Henceforth <tt>method_missing</tt> will not be hit.
227 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
228 # User.scoped_by_user_name('David')
d3eacf9 @neerajdotname Adding to AR::Base documentation about dynamically scopeded_by query
neerajdotname authored
229 #
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
230 # == 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
231 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
232 # 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
233 # 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
234 # This makes it possible to store arrays, hashes, and other non-mappable objects without doing
235 # any additional work.
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
236 #
db045db @dhh Initial
dhh authored
237 # class User < ActiveRecord::Base
238 # serialize :preferences
239 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
240 #
ca2eb16 Fix syntax error in documentation. Closes #4679. [mislav@nippur.irb.hr]
Marcel Molina authored
241 # user = User.create(:preferences => { "background" => "black", "display" => large })
db045db @dhh Initial
dhh authored
242 # User.find(user.id).preferences # => { "background" => "black", "display" => large }
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
243 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
244 # 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
245 # 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
246 #
db045db @dhh Initial
dhh authored
247 # class User < ActiveRecord::Base
66f44e6 @dhh Updated documentation for serialize
dhh authored
248 # serialize :preferences, Hash
db045db @dhh Initial
dhh authored
249 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
250 #
0591c53 @dhh Made the dynamic finders use the new find API and updated the example…
dhh authored
251 # user = User.create(:preferences => %w( one two three ))
db045db @dhh Initial
dhh authored
252 # User.find(user.id).preferences # raises SerializationTypeMismatch
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
253 #
351331f @guillermo Make serialized columns with explicit object_type return a new instan…
guillermo authored
254 # When you specify a class option, the default value for that attribute will be a new
255 # instance of that class.
256 #
257 # class User < ActiveRecord::Base
258 # serialize :preferences, OpenStruct
259 # end
260 #
261 # user = User.new
262 # user.preferences.theme_color = "red"
263 #
264 #
db045db @dhh Initial
dhh authored
265 # == Single table inheritance
266 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
267 # Active Record allows inheritance by storing the name of the class in a column that by
268 # 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
269 # This means that an inheritance looking like this:
db045db @dhh Initial
dhh authored
270 #
271 # class Company < ActiveRecord::Base; end
272 # class Firm < Company; end
273 # class Client < Company; end
274 # class PriorityClient < Client; end
275 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
276 # When you do <tt>Firm.create(:name => "37signals")</tt>, this record will be saved in
277 # 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
278 # <tt>Company.where(:name => '37signals').first</tt> and it will return a Firm object.
db045db @dhh Initial
dhh authored
279 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
280 # If you don't have a type column defined in your table, single-table inheritance won't
281 # 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
282 # for differentiating between them or reloading the right type with find.
f033833 @dhh Improving documentation...
dhh authored
283 #
db045db @dhh Initial
dhh authored
284 # Note, all the attributes for all the cases are kept in the same table. Read more:
285 # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
286 #
db045db @dhh Initial
dhh authored
287 # == Connection to multiple databases in different models
288 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
289 # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved
290 # by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this
291 # 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
292 # ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
98dc582 @lifo Merge docrails.
lifo authored
293 # and Course and all of its subclasses will use this connection instead.
db045db @dhh Initial
dhh authored
294 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
295 # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is
296 # 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
297 # will go up the class-hierarchy until a connection is found in the connection pool.
db045db @dhh Initial
dhh authored
298 #
299 # == Exceptions
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
300 #
dc4eec1 @lifo Merge docrails:
lifo authored
301 # * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record.
302 # * AdapterNotSpecified - The configuration hash used in <tt>establish_connection</tt> didn't include an
db045db @dhh Initial
dhh authored
303 # <tt>:adapter</tt> key.
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
304 # * 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
305 # non-existent adapter
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
306 # (or a bad spelling of an existing one).
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
307 # * 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
308 # specified in the association definition.
dc4eec1 @lifo Merge docrails:
lifo authored
309 # * 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
310 # * 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
311 # before querying.
dc4eec1 @lifo Merge docrails:
lifo authored
312 # * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
313 # or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
314 # nothing was found, please check its documentation for further details.
315 # * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
316 # * 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
317 # <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
318 # AttributeAssignmentError
d2fefbe @dhh Added MultiparameterAssignmentErrors and AttributeAssignmentError exc…
dhh authored
319 # 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
320 # * 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
321 # <tt>attributes=</tt> method.
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
322 # 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
323 # triggered the error.
5707027 @dhh Added better exception error when unknown column types are used with …
dhh authored
324 #
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
325 # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
dc4eec1 @lifo Merge docrails:
lifo authored
326 # 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
327 # instances in the current object space.
328 class Base
0905396 @miloops construct_finder_sql now use Arel
miloops authored
329 ##
dbbae5e @lifo Merge with docrails
lifo authored
330 # :singleton-method:
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
331 # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class,
332 # 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
333 # a class and instance level by calling +logger+.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7…
technoweenie authored
334 cattr_accessor :logger, :instance_writer => false
e694114 @jeremy Deprecation: removed Reloadable.
jeremy authored
335
dbbae5e @lifo Merge with docrails
lifo authored
336 ##
337 # :singleton-method:
a293278 @lifo Merge docrails
lifo authored
338 # Contains the database configuration - as is typically stored in config/database.yml -
339 # as a Hash.
340 #
341 # For example, the following database.yml...
0905396 @miloops construct_finder_sql now use Arel
miloops authored
342 #
a293278 @lifo Merge docrails
lifo authored
343 # development:
344 # adapter: sqlite3
345 # database: db/development.sqlite3
0905396 @miloops construct_finder_sql now use Arel
miloops authored
346 #
a293278 @lifo Merge docrails
lifo authored
347 # production:
348 # adapter: sqlite3
349 # database: db/production.sqlite3
350 #
351 # ...would result in ActiveRecord::Base.configurations to look like this:
352 #
353 # {
354 # 'development' => {
355 # 'adapter' => 'sqlite3',
356 # 'database' => 'db/development.sqlite3'
357 # },
358 # 'production' => {
359 # 'adapter' => 'sqlite3',
360 # 'database' => 'db/production.sqlite3'
361 # }
362 # }
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7…
technoweenie authored
363 cattr_accessor :configurations, :instance_writer => false
c4a3634 @jeremy Corrected @@configurations typo. #1410 [david@ruppconsulting.com]
jeremy authored
364 @@configurations = {}
365
dbbae5e @lifo Merge with docrails
lifo authored
366 ##
367 # :singleton-method:
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
368 # Accessor for the prefix type that will be prepended to every primary key column name.
369 # The options are :table_name and :table_name_with_underscore. If the first is specified,
370 # the Product class will look for "productid" instead of "id" as the primary column. If the
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
371 # latter is specified, the Product class will look for "product_id" instead of "id". Remember
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
372 # that this is a global setting for all Active Records.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7…
technoweenie authored
373 cattr_accessor :primary_key_prefix_type, :instance_writer => false
db045db @dhh Initial
dhh authored
374 @@primary_key_prefix_type = nil
375
dbbae5e @lifo Merge with docrails
lifo authored
376 ##
377 # :singleton-method:
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
378 # Accessor for the name of the prefix string to prepend to every table name. So if set
379 # to "basecamp_", all table names will be named like "basecamp_projects", "basecamp_people",
380 # etc. This is a convenient way of creating a namespace for tables in a shared database.
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
381 # By default, the prefix is the empty string.
67d1cec @pixeltrix Add the ability to specify table_name_prefix on individual modules
pixeltrix authored
382 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
383 # If you are organising your models within modules you can add a prefix to the models within
384 # a namespace by defining a singleton method in the parent module called table_name_prefix which
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
385 # returns your chosen prefix.
bab1f91 @phs table_name_prefix and table_name_suffix are class_attributes instead …
phs authored
386 class_attribute :table_name_prefix, :instance_writer => false
387 self.table_name_prefix = ""
db045db @dhh Initial
dhh authored
388
dbbae5e @lifo Merge with docrails
lifo authored
389 ##
390 # :singleton-method:
db045db @dhh Initial
dhh authored
391 # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
392 # "people_basecamp"). By default, the suffix is the empty string.
bab1f91 @phs table_name_prefix and table_name_suffix are class_attributes instead …
phs authored
393 class_attribute :table_name_suffix, :instance_writer => false
394 self.table_name_suffix = ""
db045db @dhh Initial
dhh authored
395
dbbae5e @lifo Merge with docrails
lifo authored
396 ##
397 # :singleton-method:
84a14f2 @jeremy Raise ProtectedAttributeAssignmentError in development and test envir…
jeremy authored
398 # Indicates whether table names should be the pluralized versions of the corresponding class names.
98dc582 @lifo Merge docrails.
lifo authored
399 # If true, the default table name for a Product class will be +products+. If false, it would just be +product+.
db045db @dhh Initial
dhh authored
400 # See table_name for the full rules on table/class naming. This is true, by default.
6a3b3fb @guilleiguaran Allow pluralize_table_names for individual model
guilleiguaran authored
401 class_attribute :pluralize_table_names, :instance_writer => false
402 self.pluralize_table_names = true
db045db @dhh Initial
dhh authored
403
dbbae5e @lifo Merge with docrails
lifo authored
404 ##
405 # :singleton-method:
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
406 # 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
407 # 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 #7…
technoweenie authored
408 cattr_accessor :default_timezone, :instance_writer => false
60de8c1 @dhh Added Base.default_timezone accessor that determines whether to use T…
dhh authored
409 @@default_timezone = :local
d8641ca @jeremy CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. …
jeremy authored
410
dbbae5e @lifo Merge with docrails
lifo authored
411 ##
412 # :singleton-method:
24c3599 @sstephenson Support using different database adapters for development and test wi…
sstephenson authored
413 # Specifies the format to use when dumping the database schema with Rails'
04d37b0 @smartinez87 Remove extra whitespaces
smartinez87 authored
414 # Rakefile. If :sql, the schema is dumped as (potentially database-
415 # 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
416 # ActiveRecord::Schema file which can be loaded into any database that
04d37b0 @smartinez87 Remove extra whitespaces
smartinez87 authored
417 # 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
418 # adapters for, e.g., your development and test environments.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7…
technoweenie authored
419 cattr_accessor :schema_format , :instance_writer => false
660952e @dhh CHANGED DEFAULT: ActiveRecord::Base.schema_format is now :ruby by def…
dhh authored
420 @@schema_format = :ruby
3b0e1d9 @josh Prefer string core_ext inflector methods over directly accessing Infl…
josh authored
421
dbbae5e @lifo Merge with docrails
lifo authored
422 ##
423 # :singleton-method:
155f0be @rizwanreza Changes migration number to version due to ambiguity. [#3065 state:co…
rizwanreza authored
424 # Specify whether or not to use timestamps for migration versions
bbab639 @nikz Set config.active_record.timestamped_migrations = false to have migra…
nikz authored
425 cattr_accessor :timestamped_migrations , :instance_writer => false
426 @@timestamped_migrations = true
427
bca8751 @divoxx Add ActiveRecord option to store the full class name on STI's type co…
divoxx authored
428 # Determine whether to store the full constant name including namespace when using STI
a64cc69 @neerajdotname Replacing superclass_delegating_accessoror with class_attribute.
neerajdotname authored
429 class_attribute :store_full_sti_class
1459c8c @dhh Changed ActiveRecord::Base.store_full_sti_class to be true by default…
dhh authored
430 self.store_full_sti_class = true
3b0e1d9 @josh Prefer string core_ext inflector methods over directly accessing Infl…
josh authored
431
2530d0e @lifo Added default_scope to Base [#1381 state:committed] (Paweł Kondzior)
lifo authored
432 # Stores the default scope for the class
5740d4e @jonleighton Deprecated support for passing hashes and relations to default_scope,…
jonleighton authored
433 class_attribute :default_scopes, :instance_writer => false
434 self.default_scopes = []
2530d0e @lifo Added default_scope to Base [#1381 state:committed] (Paweł Kondzior)
lifo authored
435
4b7b8d9 @jeremy Cache unserialized attributes
jeremy authored
436 # Returns a hash of all the attributes that have been specified for serialization as
437 # keys and their class restriction as values.
438 class_attribute :serialized_attributes
439 self.serialized_attributes = {}
440
d7db6a8 @joshk class inheritable attributes is used no more! all internal use of cla…
joshk authored
441 class_attribute :_attr_readonly, :instance_writer => false
442 self._attr_readonly = []
443
db045db @dhh Initial
dhh authored
444 class << self # Class methods
a9dafbb @pixeltrix Delegate first!, last!, any? and many? to scoped
pixeltrix authored
445 delegate :find, :first, :first!, :last, :last!, :all, :exists?, :any?, :many?, :to => :scoped
1187011 @jonleighton Rename first_or_new to first_or_initialize.
jonleighton authored
446 delegate :first_or_create, :first_or_create!, :first_or_initialize, :to => :scoped
a9dafbb @pixeltrix Delegate first!, last!, any? and many? to scoped
pixeltrix authored
447 delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :scoped
dc3cc6c @lifo Move batch finders to Relation
lifo authored
448 delegate :find_each, :find_in_batches, :to => :scoped
562583c @jonleighton Add ActiveRecord::Relation#uniq for toggling DISTINCT in the SQL query
jonleighton authored
449 delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins,
450 :where, :preload, :eager_load, :includes, :from, :lock, :readonly,
451 :having, :create_with, :uniq, :to => :scoped
9465b84 @lifo Rename CalculationMethods to Calculations and get rid of the old Calc…
lifo authored
452 delegate :count, :average, :minimum, :maximum, :sum, :calculate, :to => :scoped
a7fd564 @lifo Add Model.select/group/order/limit/joins/conditions/preload/eager_loa…
lifo authored
453
61bcc31 @joshsusser use GeneratedFeatureMethods module for associations
joshsusser authored
454 def inherited(child_class) #:nodoc:
455 # force attribute methods to be higher in inheritance hierarchy than other generated methods
456 child_class.generated_attribute_methods
457 child_class.generated_feature_methods
458 super
459 end
460
461 def generated_feature_methods
462 unless const_defined?(:GeneratedFeatureMethods, false)
463 include const_set(:GeneratedFeatureMethods, Module.new)
464 end
465 const_get(:GeneratedFeatureMethods)
466 end
467
04d37b0 @smartinez87 Remove extra whitespaces
smartinez87 authored
468 # Executes a custom SQL query against your database and returns all the results. The results will
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
469 # be returned as an array with columns requested encapsulated as attributes of the model you call
04d37b0 @smartinez87 Remove extra whitespaces
smartinez87 authored
470 # this method from. If you call <tt>Product.find_by_sql</tt> then the results will be returned in
a293278 @lifo Merge docrails
lifo authored
471 # a Product object with the attributes you specified in the SQL query.
edf32ce More complete documentation for find_by_sql. Closes #7912 [fearoffish]
Marcel Molina authored
472 #
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
473 # If you call a complicated SQL query which spans multiple tables the columns specified by the
474 # SELECT will be attributes of the model, whether or not they are columns of the corresponding
edf32ce More complete documentation for find_by_sql. Closes #7912 [fearoffish]
Marcel Molina authored
475 # table.
476 #
04d37b0 @smartinez87 Remove extra whitespaces
smartinez87 authored
477 # The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be
478 # no database agnostic conversions performed. This should be a last resort because using, for example,
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
479 # MySQL specific terms will lock you to using that particular database engine or require you to
a293278 @lifo Merge docrails
lifo authored
480 # change your call if you switch engines.
edf32ce More complete documentation for find_by_sql. Closes #7912 [fearoffish]
Marcel Molina authored
481 #
482 # ==== Examples
98dc582 @lifo Merge docrails.
lifo authored
483 # # A simple SQL query spanning multiple tables
edf32ce More complete documentation for find_by_sql. Closes #7912 [fearoffish]
Marcel Molina authored
484 # Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
485 # > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
486 #
487 # # You can use the same string replacement techniques as you can with ActiveRecord#find
488 # Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
045ca30 @mjy fixes a missmatched column in example
mjy authored
489 # > [#<Post:0x36bff9c @attributes={"title"=>"The Cheap Man Buys Twice"}>, ...]
e73b0b8 @tenderlove renaming bind_values to binds where it makes sense
tenderlove authored
490 def find_by_sql(sql, binds = [])
491 connection.select_all(sanitize_sql(sql), "#{name} Load", binds).collect! { |record| instantiate(record) }
db045db @dhh Initial
dhh authored
492 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
493
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
494 # Creates an object (or multiple objects) and saves it to the database, if validations pass.
a23bea7 Document API for create's attributes parameter and provide examples. …
Marcel Molina authored
495 # The resulting object is returned whether the object was saved successfully to the database or not.
496 #
04d37b0 @smartinez87 Remove extra whitespaces
smartinez87 authored
497 # The +attributes+ parameter can be either be a Hash or an Array of Hashes. These Hashes describe the
a23bea7 Document API for create's attributes parameter and provide examples. …
Marcel Molina authored
498 # attributes on the objects that are to be created.
499 #
7c5ae0a @joshk Added mass-assignment security :as and :without_protection support to…
joshk authored
500 # +create+ respects mass-assignment security and accepts either +:as+ or +:without_protection+ options
501 # in the +options+ parameter.
502 #
a23bea7 Document API for create's attributes parameter and provide examples. …
Marcel Molina authored
503 # ==== Examples
504 # # Create a single new object
505 # User.create(:first_name => 'Jamie')
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new alrea…
dhh authored
506 #
b2451f4 @joshk renamed mass-assignment scopes to roles, updated code, tests, docs an…
joshk authored
507 # # Create 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
508 # User.create({ :first_name => 'Jamie', :is_admin => true }, :as => :admin)
509 #
510 # # Create a single new object bypassing mass-assignment security
511 # User.create({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true)
512 #
a23bea7 Document API for create's attributes parameter and provide examples. …
Marcel Molina authored
513 # # Create an Array of new objects
dc4eec1 @lifo Merge docrails:
lifo authored
514 # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new alrea…
dhh authored
515 #
516 # # Create a single object and pass it into a block to set other attributes.
517 # User.create(:first_name => 'Jamie') do |u|
518 # u.is_admin = false
519 # end
520 #
521 # # Creating an Array of new objects using a block, where the block is executed for each object:
dc4eec1 @lifo Merge docrails:
lifo authored
522 # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u|
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new alrea…
dhh authored
523 # u.is_admin = false
3b0e1d9 @josh Prefer string core_ext inflector methods over directly accessing Infl…
josh authored
524 # end
7c5ae0a @joshk Added mass-assignment security :as and :without_protection support to…
joshk authored
525 def create(attributes = nil, options = {}, &block)
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#…
dhh authored
526 if attributes.is_a?(Array)
7c5ae0a @joshk Added mass-assignment security :as and :without_protection support to…
joshk authored
527 attributes.collect { |attr| create(attr, options, &block) }
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#…
dhh authored
528 else
f956759 @hmcfletch fix after_initialize edge case (close #2074 and close #2175)
hmcfletch authored
529 object = new(attributes, options, &block)
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#…
dhh authored
530 object.save
531 object
532 end
db045db @dhh Initial
dhh authored
533 end
534
535 # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
536 # The use of this method should be restricted to complicated SQL queries that can't be executed
04d37b0 @smartinez87 Remove extra whitespaces
smartinez87 authored
537 # using the ActiveRecord::Calculations class methods. Look into those before using this.
ee614d6 Add documentation caveat about when to use count_by_sql. Closes #8090…
Marcel Molina authored
538 #
a293278 @lifo Merge docrails
lifo authored
539 # ==== Parameters
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
540 #
dc4eec1 @lifo Merge docrails:
lifo authored
541 # * +sql+ - An SQL statement which should return a count query from the database, see the example below.
ee614d6 Add documentation caveat about when to use count_by_sql. Closes #8090…
Marcel Molina authored
542 #
543 # ==== Examples
544 #
e17bf81 @jamis Fix typo in count_by_sql documentation #1969 [Alexey Verkhovsky]
jamis authored
545 # Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
db045db @dhh Initial
dhh authored
546 def count_by_sql(sql)
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in r…
dhh authored
547 sql = sanitize_conditions(sql)
caaf40d @dhh Added AbstractAdapter#select_value and AbstractAdapter#select_values …
dhh authored
548 connection.select_value(sql, "#{name} Count").to_i
db045db @dhh Initial
dhh authored
549 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
550
74f7e17 @neerajdotname fixing documentation
neerajdotname authored
551 # Attributes listed as readonly will be used to create a new record but update operations will
552 # ignore these fields.
606088d @eac Mass assignment security refactoring
eac authored
553 def attr_readonly(*attributes)
d7db6a8 @joshk class inheritable attributes is used no more! all internal use of cla…
joshk authored
554 self._attr_readonly = Set.new(attributes.map { |a| a.to_s }) + (self._attr_readonly || [])
db045db @dhh Initial
dhh authored
555 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
556
606088d @eac Mass assignment security refactoring
eac authored
557 # Returns an array of all the attributes that have been specified as readonly.
558 def readonly_attributes
d7db6a8 @joshk class inheritable attributes is used no more! all internal use of cla…
joshk authored
559 self._attr_readonly
db045db @dhh Initial
dhh authored
560 end
561
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
562 # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object,
563 # then specify the name of that attribute using this method and it will be handled automatically.
564 # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that
98dc582 @lifo Merge docrails.
lifo authored
565 # class on retrieval or SerializationTypeMismatch will be raised.
1a0cdf7 @dhh Docfix (closes #8096)
dhh authored
566 #
a293278 @lifo Merge docrails
lifo authored
567 # ==== Parameters
1a0cdf7 @dhh Docfix (closes #8096)
dhh authored
568 #
dc4eec1 @lifo Merge docrails:
lifo authored
569 # * +attr_name+ - The field name that should be serialized.
570 # * +class_name+ - Optional, class name that the object type should be equal to.
1a0cdf7 @dhh Docfix (closes #8096)
dhh authored
571 #
572 # ==== Example
573 # # Serialize a preferences attribute
55105c4 @txus Fix missing inheritance from AR::Base in docs
txus authored
574 # class User < ActiveRecord::Base
1a0cdf7 @dhh Docfix (closes #8096)
dhh authored
575 # serialize :preferences
576 # end
db045db @dhh Initial
dhh authored
577 def serialize(attr_name, class_name = Object)
ebe485f @tenderlove serialize can take an arbitrary code object
tenderlove authored
578 coder = if [:load, :dump].all? { |x| class_name.respond_to?(x) }
579 class_name
580 else
581 Coders::YAMLColumn.new(class_name)
582 end
583
c567ccb @rsim bugfix for serialized_attributes to be class specific
rsim authored
584 # merge new serialized attribute and create new hash to ensure that each class in inheritance hierarchy
585 # has its own hash of own serialized attributes
586 self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder)
db045db @dhh Initial
dhh authored
587 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
588
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
589 # Guesses the table name (in forced lower-case) based on the name of the class in the
590 # inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
591 # looks like: Reply < Message < ActiveRecord::Base, then Message is used
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
592 # to guess the table name even when called on Reply. The rules used to do the guess
593 # are handled by the Inflector class in Active Support, which knows almost all common
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
594 # English inflections. You can add new inflections in config/initializers/inflections.rb.
db045db @dhh Initial
dhh authored
595 #
14101c7 @jeremy Nested classes are given table names prefixed by the singular form of…
jeremy authored
596 # Nested classes are given table names prefixed by the singular form of
98dc582 @lifo Merge docrails.
lifo authored
597 # the parent's table name. Enclosing modules are not considered.
598 #
599 # ==== Examples
d64832c Give examples for what tables should be called for models inside a mo…
Marcel Molina authored
600 #
b134e0f @Karunakar Documentation Error Fixed for ticket #839
Karunakar authored
601 # class Invoice < ActiveRecord::Base
602 # end
603 #
14101c7 @jeremy Nested classes are given table names prefixed by the singular form of…
jeremy authored
604 # file class table_name
605 # invoice.rb Invoice invoices
d64832c Give examples for what tables should be called for models inside a mo…
Marcel Molina authored
606 #
b134e0f @Karunakar Documentation Error Fixed for ticket #839
Karunakar authored
607 # class Invoice < ActiveRecord::Base
608 # class Lineitem < ActiveRecord::Base
609 # end
610 # end
611 #
d64832c Give examples for what tables should be called for models inside a mo…
Marcel Molina authored
612 # file class table_name
613 # invoice.rb Invoice::Lineitem invoice_lineitems
614 #
b134e0f @Karunakar Documentation Error Fixed for ticket #839
Karunakar authored
615 # module Invoice
616 # class Lineitem < ActiveRecord::Base
617 # end
618 # end
619 #
d64832c Give examples for what tables should be called for models inside a mo…
Marcel Molina authored
620 # file class table_name
621 # invoice/lineitem.rb Invoice::Lineitem lineitems
db045db @dhh Initial
dhh authored
622 #
98dc582 @lifo Merge docrails.
lifo authored
623 # Additionally, the class-level +table_name_prefix+ is prepended and the
04d37b0 @smartinez87 Remove extra whitespaces
smartinez87 authored
624 # +table_name_suffix+ is appended. So if you have "myapp_" as a prefix,
14101c7 @jeremy Nested classes are given table names prefixed by the singular form of…
jeremy authored
625 # the table name guess for an Invoice class becomes "myapp_invoices".
626 # Invoice::Lineitem becomes "myapp_invoice_lineitems".
627 #
0b72a04 @jonleighton Deprecate set_table_name in favour of self.table_name= or defining yo…
jonleighton authored
628 # You can also set your own table name explicitly:
db045db @dhh Initial
dhh authored
629 #
630 # class Mouse < ActiveRecord::Base
0b72a04 @jonleighton Deprecate set_table_name in favour of self.table_name= or defining yo…
jonleighton authored
631 # self.table_name = "mice"
db045db @dhh Initial
dhh authored
632 # end
0b72a04 @jonleighton Deprecate set_table_name in favour of self.table_name= or defining yo…
jonleighton authored
633 #
634 # Alternatively, you can override the table_name method to define your
635 # own computation. (Possibly using <tt>super</tt> to manipulate the default
636 # table name.) Example:
637 #
638 # class Post < ActiveRecord::Base
639 # def self.table_name
640 # "special_" + super
641 # end
642 # end
643 # Post.table_name # => "special_posts"
dcc4868 @dhh Fixed that Base.table_name would expect a parameter when used in has_…
dhh authored
644 def table_name
0b72a04 @jonleighton Deprecate set_table_name in favour of self.table_name= or defining yo…
jonleighton authored
645 reset_table_name unless defined?(@table_name)
646 @table_name
647 end
648
649 # Sets the table name explicitly. Example:
650 #
651 # class Project < ActiveRecord::Base
652 # self.table_name = "project"
653 # end
654 #
655 # You can also just define your own <tt>self.table_name</tt> method; see
656 # the documentation for ActiveRecord::Base#table_name.
657 def table_name=(value)
658 @quoted_table_name = nil
659 @arel_table = nil
660 @table_name = value
661 @relation = Relation.new(self, arel_table)
662 end
663
664 def set_table_name(value = nil, &block) #:nodoc:
665 if block
666 ActiveSupport::Deprecation.warn(
667 "Calling set_table_name is deprecated. If you need to lazily evaluate " \
668 "the table name, define your own `self.table_name` class method. You can use `super` " \
669 "to get the default table name where you would have called `original_table_name`."
670 )
671
672 @quoted_table_name = nil
673 define_attr_method :table_name, value, &block
674 @arel_table = nil
675 @relation = Relation.new(self, arel_table)
676 else
677 ActiveSupport::Deprecation.warn(
678 "Calling set_table_name is deprecated. Please use `self.table_name = 'the_name'` instead."
679 )
680
681 self.table_name = value
682 end
d736568 Speed up the setting of table_name. Closes #2428.
Marcel Molina authored
683 end
684
8d82bef @tchandy Documentation for #quoted_table_name method
tchandy authored
685 # Returns a quoted version of the table name, used to construct SQL statements.
798d282 @lifo Cache quoted_table_name
lifo authored
686 def quoted_table_name
687 @quoted_table_name ||= connection.quote_table_name(table_name)
688 end
689
4a8c880 @fxn refactors AR::Base#reset_table_name
fxn authored
690 # Computes the table name, (re)sets it internally, and returns it.
fed7d33 @dhh Fixed documentation
dhh authored
691 def reset_table_name #:nodoc:
0b72a04 @jonleighton Deprecate set_table_name in favour of self.table_name= or defining yo…
jonleighton authored
692 if superclass.abstract_class?
693 self.table_name = superclass.table_name || compute_table_name
694 elsif abstract_class?
695 self.table_name = superclass == Base ? nil : superclass.table_name
696 else
697 self.table_name = compute_table_name
698 end
db045db @dhh Initial
dhh authored
699 end
700
5f7bc47 @wycats Rename modularized_table_name_prefix to full_table_name_prefix [#4032…
wycats authored
701 def full_table_name_prefix #:nodoc:
67d1cec @pixeltrix Add the ability to specify table_name_prefix on individual modules
pixeltrix authored
702 (parents.detect{ |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix
703 end
704
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
705 # Defines the column name for use with single table inheritance. Use
74f7e17 @neerajdotname fixing documentation
neerajdotname authored
706 # <tt>set_inheritance_column</tt> to set a different value.
db045db @dhh Initial
dhh authored
707 def inheritance_column
c8a2dd3 @tenderlove no need to freeze this string
tenderlove authored
708 @inheritance_column ||= "type"
db045db @dhh Initial
dhh authored
709 end
710
04d37b0 @smartinez87 Remove extra whitespaces
smartinez87 authored
711 # Lazy-set the sequence name to the connection's default. This method
7c8f3ed @jeremy r4325@asus: jeremy | 2005-11-12 03:57:46 -0800
jeremy authored
712 # is only ever called once since set_sequence_name overrides it.
fed7d33 @dhh Fixed documentation
dhh authored
713 def sequence_name #:nodoc:
7c8f3ed @jeremy r4325@asus: jeremy | 2005-11-12 03:57:46 -0800
jeremy authored
714 reset_sequence_name
715 end
716
fed7d33 @dhh Fixed documentation
dhh authored
717 def reset_sequence_name #:nodoc:
7c8f3ed @jeremy r4325@asus: jeremy | 2005-11-12 03:57:46 -0800
jeremy authored
718 default = connection.default_sequence_name(table_name, primary_key)
719 set_sequence_name(default)
720 default
14ea312 @dhh Made Oracle a first-class connection adapter by adhering closer to id…
dhh authored
721 end
722
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindin…
dhh authored
723 # Sets the name of the inheritance column to use to the given value,
724 # or (if the value # is nil or false) to the value returned by the
4eab375 @dhh Finished polishing API docs
dhh authored
725 # given block.
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindin…
dhh authored
726 #
727 # class Project < ActiveRecord::Base
728 # set_inheritance_column do
729 # original_inheritance_column + "_id"
730 # end
731 # end
c9c1852 @dhh Making ActiveRecord faster [skaes]
dhh authored
732 def set_inheritance_column(value = nil, &block)
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindin…
dhh authored
733 define_attr_method :inheritance_column, value, &block
734 end
735 alias :inheritance_column= :set_inheritance_column
736
14ea312 @dhh Made Oracle a first-class connection adapter by adhering closer to id…
dhh authored
737 # Sets the name of the sequence to use when generating ids to the given
738 # value, or (if the value is nil or false) to the value returned by the
7117fdb @jeremy r3616@asus: jeremy | 2005-09-26 23:09:28 -0700
jeremy authored
739 # given block. This is required for Oracle and is useful for any
740 # database which relies on sequences for primary key generation.
14ea312 @dhh Made Oracle a first-class connection adapter by adhering closer to id…
dhh authored
741 #
2076dca @jeremy r3095@asus: jeremy | 2005-11-15 22:40:51 -0800
jeremy authored
742 # If a sequence name is not explicitly set when using Oracle or Firebird,
743 # it will default to the commonly used pattern of: #{table_name}_seq
744 #
745 # If a sequence name is not explicitly set when using PostgreSQL, it
746 # will discover the sequence corresponding to your primary key for you.
14ea312 @dhh Made Oracle a first-class connection adapter by adhering closer to id…
dhh authored
747 #
748 # class Project < ActiveRecord::Base
749 # set_sequence_name "projectseq" # default would have been "project_seq"
750 # end
c9c1852 @dhh Making ActiveRecord faster [skaes]
dhh authored
751 def set_sequence_name(value = nil, &block)
14ea312 @dhh Made Oracle a first-class connection adapter by adhering closer to id…
dhh authored
752 define_attr_method :sequence_name, value, &block
753 end
754 alias :sequence_name= :set_sequence_name
755
816f37a @dhh Added migration support to SQL Server adapter (please someone do the …
dhh authored
756 # Indicates whether the table associated with this class exists
757 def table_exists?
8877ab5 @tarmo Added AbstractAdapter#table_exists? and made AbstractAdapter#table im…
tarmo authored
758 connection.table_exists?(table_name)
816f37a @dhh Added migration support to SQL Server adapter (please someone do the …
dhh authored
759 end
760
db045db @dhh Initial
dhh authored
761 # Returns an array of column objects for the table associated with this class.
762 def columns
b3407c8 @jonleighton Don't require a DB connection when setting primary key.
jonleighton authored
763 if defined?(@primary_key)
bd2f5c0 @tenderlove pushing caching and visitors down to the connection
tenderlove authored
764 connection.schema_cache.primary_keys[table_name] ||= primary_key
b3407c8 @jonleighton Don't require a DB connection when setting primary key.
jonleighton authored
765 end
766
bd2f5c0 @tenderlove pushing caching and visitors down to the connection
tenderlove authored
767 connection.schema_cache.columns[table_name]
db045db @dhh Initial
dhh authored
768 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
769
3b4450b @NZKoz Docs fix for columns_hash [bradediger]
NZKoz authored
770 # Returns a hash of column objects for the table associated with this class.
db045db @dhh Initial
dhh authored
771 def columns_hash
bd2f5c0 @tenderlove pushing caching and visitors down to the connection
tenderlove authored
772 connection.schema_cache.columns_hash[table_name]
db045db @dhh Initial
dhh authored
773 end
d0bd3b5 @jeremy Return PostgreSQL columns in the order they are declared #1374 (perlg…
jeremy authored
774
45b7209 @tenderlove cache column defaults for AR object instantiation
tenderlove authored
775 # Returns a hash where the keys are column names and the values are
776 # default values when instantiating the AR object for this table.
777 def column_defaults
bd2f5c0 @tenderlove pushing caching and visitors down to the connection
tenderlove authored
778 connection.schema_cache.column_defaults[table_name]
45b7209 @tenderlove cache column defaults for AR object instantiation
tenderlove authored
779 end
780
fed7d33 @dhh Fixed documentation
dhh authored
781 # Returns an array of column names as strings.
49d0f0c @dhh Speeded up eager loading a whole bunch
dhh authored
782 def column_names
d0bd3b5 @jeremy Return PostgreSQL columns in the order they are declared #1374 (perlg…
jeremy authored
783 @column_names ||= columns.map { |column| column.name }
49d0f0c @dhh Speeded up eager loading a whole bunch
dhh authored
784 end
db045db @dhh Initial
dhh authored
785
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
786 # Returns an array of column objects where the primary id, all columns ending in "_id" or "_count",
787 # and columns used for single table inheritance have been removed.
db045db @dhh Initial
dhh authored
788 def content_columns
c0899bc Add convenience predicate methods on Column class. In partial fullfil…
Marcel Molina authored
789 @content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column }
db045db @dhh Initial
dhh authored
790 end
791
792 # 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
793 # 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
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
794 # is available.
fed7d33 @dhh Fixed documentation
dhh authored
795 def column_methods_hash #:nodoc:
d0bd3b5 @jeremy Return PostgreSQL columns in the order they are declared #1374 (perlg…
jeremy authored
796 @dynamic_methods_hash ||= column_names.inject(Hash.new(false)) do |methods, attr|
3ab3a70 @jeremy Clarify semantics of ActiveRecord::Base#respond_to? Closes #2560.
jeremy authored
797 attr_name = attr.to_s
798 methods[attr.to_sym] = attr_name
799 methods["#{attr}=".to_sym] = attr_name
800 methods["#{attr}?".to_sym] = attr_name
801 methods["#{attr}_before_type_cast".to_sym] = attr_name
db045db @dhh Initial
dhh authored
802 methods
803 end
804 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
805
a293278 @lifo Merge docrails
lifo authored
806 # Resets all the cached information about columns, which will cause them
807 # to be reloaded on the next request.
808 #
809 # The most common usage pattern for this method is probably in a migration,
810 # when just after creating a table you want to populate it with some default
811 # values, eg:
812 #
813 # class CreateJobLevels < ActiveRecord::Migration
55b203d @amatsuda self.up, self.down => up, down
amatsuda authored
814 # def up
a293278 @lifo Merge docrails
lifo authored
815 # create_table :job_levels do |t|
816 # t.integer :id
817 # t.string :name
818 #
819 # t.timestamps
820 # end
821 #
822 # JobLevel.reset_column_information
823 # %w{assistant executive manager director}.each do |type|
824 # JobLevel.create(:name => type)
825 # end
826 # end
827 #
55b203d @amatsuda self.up, self.down => up, down
amatsuda authored
828 # def down
a293278 @lifo Merge docrails
lifo authored
829 # drop_table :job_levels
830 # end
831 # end
1314f48 @dhh Added methods for resetting the cached information on classes that yo…
dhh authored
832 def reset_column_information
d6b16bb @tenderlove one more mysql test left!
tenderlove authored
833 connection.clear_cache!
e129c56 @josh Wrap up attribute method reset concerns in 'undefine_attribute_methods'
josh authored
834 undefine_attribute_methods
bd2f5c0 @tenderlove pushing caching and visitors down to the connection
tenderlove authored
835 connection.schema_cache.clear_table_cache!(table_name) if table_exists?
c94651f @tenderlove almost fisted
tenderlove authored
836
ee34b4c @tenderlove share column cache among subclasses, only look up columns per AR::Bas…
tenderlove authored
837 @column_names = @content_columns = @dynamic_methods_hash = @inheritance_column = nil
23a3ba4 @tenderlove Revert "ARel only requires the connection from the AR class. Simply r…
tenderlove authored
838 @arel_engine = @relation = nil
1314f48 @dhh Added methods for resetting the cached information on classes that yo…
dhh authored
839 end
840
7423a71 @tenderlove allow AR caches to be cleared, clear them on class reloading
tenderlove authored
841 def clear_cache! # :nodoc:
bd2f5c0 @tenderlove pushing caching and visitors down to the connection
tenderlove authored
842 connection.schema_cache.clear!
1314f48 @dhh Added methods for resetting the cached information on classes that yo…
dhh authored
843 end
844
ce48b31 @spastorino Makes validates_acceptance_of to not override database fields [#4460 …
spastorino authored
845 def attribute_method?(attribute)
209ab7e @josevalim Fix failing test.
josevalim authored
846 super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, '')))
ce48b31 @spastorino Makes validates_acceptance_of to not override database fields [#4460 …
spastorino authored
847 end
848
2470392 @smartinez87 Add doc to #attribute_names
smartinez87 authored
849 # Returns an array of column names as strings if it's not
850 # an abstract class and table exists.
851 # Otherwise it returns an empty array.
5ca67ec @sikachu Add ActiveRecord::attribute_names to retrieve a list of attribute nam…
sikachu authored
852 def attribute_names
853 @attribute_names ||= if !abstract_class? && table_exists?
854 column_names
855 else
856 []
857 end
858 end
859
e714b49 @josevalim Move validator, human_name and human_attribute_name to ActiveModel, r…
josevalim authored
860 # Set the lookup ancestors for ActiveModel.
861 def lookup_ancestors #:nodoc:
ffeab4e Cleaned up ActiveRecord i18n scoping
Iain Hecker authored
862 klass = self
863 classes = [klass]
f978c4b @neerajdotname remove the rescue block by returning a not asking Base for lookup_anc…
neerajdotname authored
864 return classes if klass == ActiveRecord::Base
865
0905396 @miloops construct_finder_sql now use Arel
miloops authored
866 while klass != klass.base_class
ffeab4e Cleaned up ActiveRecord i18n scoping
Iain Hecker authored
867 classes << klass = klass.superclass
868 end
869 classes
870 end
871
e714b49 @josevalim Move validator, human_name and human_attribute_name to ActiveModel, r…
josevalim authored
872 # Set the i18n scope to overwrite ActiveModel.
873 def i18n_scope #:nodoc:
874 :activerecord
db045db @dhh Initial
dhh authored
875 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
876
06afb8c @jeremy Subclasses of an abstract class work with single-table inheritance. R…
jeremy authored
877 # True if this isn't a concrete subclass needing a STI type condition.
878 def descends_from_active_record?
879 if superclass.abstract_class?
880 superclass.descends_from_active_record?
881 else
882 superclass == Base || !columns_hash.include?(inheritance_column)
883 end
db045db @dhh Initial
dhh authored
884 end
885
b4ec990 @NZKoz Cache the descends_from_activerecord? call to speed up query generati…
NZKoz authored
886 def finder_needs_type_condition? #:nodoc:
887 # This is like this because benchmarking justifies the strange :false stuff
888 :true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true)
889 end
890
018a88c @amatsuda missing parentheses
amatsuda authored
891 # Returns a string like 'Post(id:integer, title:string, body:text)'
52a9e50 @dhh Added ActiveRecord::Base.inspect to return a column-view like #<Post …
dhh authored
892 def inspect
d0360a4 @jeremy Base.inspect handles Base itself and abstract_class? Don't use #<Foo…
jeremy authored
893 if self == Base
894 super
895 elsif abstract_class?
896 "#{super}(abstract)"
bb94ce9 @NZKoz Let inspect on AR classes work when the table doesn't exist. Closes #…
NZKoz authored
897 elsif table_exists?
d0360a4 @jeremy Base.inspect handles Base itself and abstract_class? Don't use #<Foo…
jeremy authored
898 attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', '
899 "#{super}(#{attr_list})"
bb94ce9 @NZKoz Let inspect on AR classes work when the table doesn't exist. Closes #…
NZKoz authored
900 else
901 "#{super}(Table doesn't exist)"
d0360a4 @jeremy Base.inspect handles Base itself and abstract_class? Don't use #<Foo…
jeremy authored
902 end
52a9e50 @dhh Added ActiveRecord::Base.inspect to return a column-view like #<Post …
dhh authored
903 end
904
b445ab9 @NZKoz Rename quote to quote_value so the name can be used in AR models. #36…
NZKoz authored
905 def quote_value(value, column = nil) #:nodoc:
b2c0ddf Add support for FrontBase (http://www.frontbase.com/) with a new adap…
Marcel Molina authored
906 connection.quote(value,column)
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
907 end
908
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobS…
Marcel Molina authored
909 # Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>.
4eab375 @dhh Finished polishing API docs
dhh authored
910 def sanitize(object) #:nodoc:
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
911 connection.quote(object)
db045db @dhh Initial
dhh authored
912 end
913
97849de @dhh Fixed that association proxies would fail === tests like PremiumSubsc…
dhh authored
914 # Overwrite the default class equality method to provide support for association proxies.
915 def ===(object)
916 object.is_a?(self)
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
917 end
b840e4e Deprecated ActiveRecord::Base.threaded_connection in favor of ActiveR…
Marcel Molina authored
918
301dd3d @miloops Use hash[:Post][1] style identity maps for each table.
miloops authored
919 def symbolized_base_class
920 @symbolized_base_class ||= base_class.to_s.to_sym
921 end
922
5d6c8d5 @josevalim Revert "Revert the merge because tests did not pass."
josevalim authored
923 def symbolized_sti_name
ba23bf4 @josevalim Class.new.name returns an empty string on 1.8
josevalim authored
924 @symbolized_sti_name ||= sti_name.present? ? sti_name.to_sym : symbolized_base_class
5d6c8d5 @josevalim Revert "Revert the merge because tests did not pass."
josevalim authored
925 end
926
d2f4750 @jamis Add AR::Base.base_class for querying the ancestor AR::Base subclass […
jamis authored
927 # Returns the base AR subclass that this class descends from. If A
928 # extends AR::Base, A.base_class will return A. If B descends from A
929 # through some arbitrarily deep hierarchy, B.base_class will return A.
d10aaef @neerajdotname clarifying the comments regarding base_class declaration
neerajdotname authored
930 #
931 # If B < A and C < B and if A is an abstract_class then both B.base_class
932 # and C.base_class would return B as the answer since A is an abstract_class.
d2f4750 @jamis Add AR::Base.base_class for querying the ancestor AR::Base subclass […
jamis authored
933 def base_class
934 class_of_active_record_descendant(self)
935 end
936
98dc582 @lifo Merge docrails.
lifo authored
937 # Set this to true if this is an abstract class (see <tt>abstract_class?</tt>).
def7460 @technoweenie Added Base.abstract_class? that marks which classes are not part of t…
technoweenie authored
938 attr_accessor :abstract_class
939
d10aaef @neerajdotname clarifying the comments regarding base_class declaration
neerajdotname authored
940 # Returns whether this class is an abstract class or not.
def7460 @technoweenie Added Base.abstract_class? that marks which classes are not part of t…
technoweenie authored
941 def abstract_class?
8b5f4e4 @jeremy Ruby 1.9 compat: fix warnings, shadowed block vars, and unitialized i…
jeremy authored
942 defined?(@abstract_class) && @abstract_class == true
def7460 @technoweenie Added Base.abstract_class? that marks which classes are not part of t…
technoweenie authored
943 end
944
4f39382 @lifo Ensure that respond_to? considers dynamic finder methods. Closes #115…
lifo authored
945 def respond_to?(method_id, include_private = false)
143f5fb @joshsusser refactor dynamic finder name matching into its own class
joshsusser authored
946 if match = DynamicFinderMatch.match(method_id)
947 return true if all_attributes_exists?(match.attribute_names)
66ee589 @yaroslav Introduce dynamic scopes for ActiveRecord: you can now use class meth…
yaroslav authored
948 elsif match = DynamicScopeMatch.match(method_id)
949 return true if all_attributes_exists?(match.attribute_names)
4f39382 @lifo Ensure that respond_to? considers dynamic finder methods. Closes #115…
lifo authored
950 end
c3aa2bc @Manfred Ensure nested with_scope merges conditions inside out [#2193 state:re…
Manfred authored
951
4f39382 @lifo Ensure that respond_to? considers dynamic finder methods. Closes #115…
lifo authored
952 super
953 end
954
72483c0 @technoweenie Add ActiveRecord::Base.sti_name that checks ActiveRecord::Base#store_…
technoweenie authored
955 def sti_name
956 store_full_sti_class ? name : name.demodulize
957 end
958
6e3bee6 @lifo Cache Model.arel_table
lifo authored
959 def arel_table
84f71e4 @dmathieu don't reinitialize the arel_table unless the table_name changes
dmathieu authored
960 @arel_table ||= Arel::Table.new(table_name, arel_engine)
d2c4b3b @lifo Rename Model.engine to active_relation_engine. Cache arel_table and t…
lifo authored
961 end
962
5a52523 @lifo Rename active_relation_engine -> arel_engine and active_relation_tabl…
lifo authored
963 def arel_engine
964 @arel_engine ||= begin
a115b5d @lifo Ensure using proper engine for Arel::Table
lifo authored
965 if self == ActiveRecord::Base
23a3ba4 @tenderlove Revert "ARel only requires the connection from the AR class. Simply r…
tenderlove authored
966 ActiveRecord::Base
a115b5d @lifo Ensure using proper engine for Arel::Table
lifo authored
967 else
45edeed @tenderlove Arel::Sql::Engine.new does not do anything anymore
tenderlove authored
968 connection_handler.connection_pools[name] ? self : superclass.arel_engine
a115b5d @lifo Ensure using proper engine for Arel::Table
lifo authored
969 end
970 end
77c23b2 @lifo Use PredicateBuilder for sql hash sanitization
lifo authored
971 end
972
bd1666a @josevalim Add scoping and unscoped as the syntax to replace the old with_scope …
josevalim authored
973 # Returns a scope for this class without taking into account the default_scope.
974 #
975 # class Post < ActiveRecord::Base
5740d4e @jonleighton Deprecated support for passing hashes and relations to default_scope,…
jonleighton authored
976 # def self.default_scope
977 # where :published => true
978 # end
bd1666a @josevalim Add scoping and unscoped as the syntax to replace the old with_scope …
josevalim authored
979 # end
980 #
981 # Post.all # Fires "SELECT * FROM posts WHERE published = true"
982 # Post.unscoped.all # Fires "SELECT * FROM posts"
983 #
984 # This method also accepts a block meaning that all queries inside the block will
985 # not use the default_scope:
986 #
987 # Post.unscoped {
2bfeda3 fix bug in usage example of #unscoped
Corin Langosch authored
988 # Post.limit(10) # Fires "SELECT * FROM posts LIMIT 10"
bd1666a @josevalim Add scoping and unscoped as the syntax to replace the old with_scope …
josevalim authored
989 # }
990 #
96bae30 @pahanix Replace rudimentary named_scope with scope. [#6052 state:resolved]
pahanix authored
991 # It is recommended to use block form of unscoped because chaining unscoped with <tt>scope</tt>
992 # does not work. Assuming that <tt>published</tt> is a <tt>scope</tt> following two statements are same.
13ebf69 @neerajdotname unscoped does not work when chained with named_scope
neerajdotname authored
993 #
9b61004 @carlosantoniodasilva Cleanup deprecation warnings in active record
carlosantoniodasilva authored
994 # Post.unscoped.published
995 # Post.published
3ac6646 @fxn :nodoc:s #unscoped until its behavior is more clear, now sometimes wo…
fxn authored
996 def unscoped #:nodoc:
bd1666a @josevalim Add scoping and unscoped as the syntax to replace the old with_scope …
josevalim authored
997 block_given? ? relation.scoping { yield } : relation
998 end
999
4e67bf2 @pixeltrix Reset default scope in Thread.current when class is unloaded [#5497 s…
pixeltrix authored
1000 def before_remove_const #:nodoc:
5740d4e @jonleighton Deprecated support for passing hashes and relations to default_scope,…
jonleighton authored
1001 self.current_scope = nil
4e67bf2 @pixeltrix Reset default scope in Thread.current when class is unloaded [#5497 s…
pixeltrix authored
1002 end
1003
8c71e8b @tenderlove lazily instantiate AR objects in order to avoid NoMethodErrors
tenderlove authored
1004 # Finder methods must instantiate through this method to work with the
1005 # single-table inheritance model that makes it possible to create
1006 # objects of different types from the same table.
8ee0b44 @miloops Merge remote branch 'rails/master' into identity_map
miloops authored
1007 def instantiate(record)
1008 sti_class = find_sti_class(record[inheritance_column])
6474765 @jonleighton Revert "Raise error on unknown primary key."
jonleighton authored
1009 record_id = sti_class.primary_key && record[sti_class.primary_key]
24485b9 @swistak Separated initialization
swistak authored
1010
8ee0b44 @miloops Merge remote branch 'rails/master' into identity_map
miloops authored
1011 if ActiveRecord::IdentityMap.enabled? && record_id
1012 if (column = sti_class.columns_hash[sti_class.primary_key]) && column.number?
1013 record_id = record_id.to_i
1014 end
1015 if instance = IdentityMap.get(sti_class, record_id)
1016 instance.reinit_with('attributes' => record)
c357f84 @swistak IdentityMap - adding and removing of records on create/update
swistak authored
1017 else
24485b9 @swistak Separated initialization
swistak authored
1018 instance = sti_class.allocate.init_with('attributes' => record)
8ee0b44 @miloops Merge remote branch 'rails/master' into identity_map
miloops authored
1019 IdentityMap.add(instance)
c357f84 @swistak IdentityMap - adding and removing of records on create/update
swistak authored
1020 end
8ee0b44 @miloops Merge remote branch 'rails/master' into identity_map
miloops authored
1021 else
1022 instance = sti_class.allocate.init_with('attributes' => record)
1023 end
1024
1025 instance
8c71e8b @tenderlove lazily instantiate AR objects in order to avoid NoMethodErrors
tenderlove authored
1026 end
c357f84 @swistak IdentityMap - adding and removing of records on create/update
swistak authored
1027
db045db @dhh Initial
dhh authored
1028 private
57d750e @josevalim Make relation a private method.
josevalim authored
1029
1030 def relation #:nodoc:
1031 @relation ||= Relation.new(self, arel_table)
62b084f @jonleighton Specify the STI type condition using SQL IN rather than a whole load …
jonleighton authored
1032
1033 if finder_needs_type_condition?
1034 @relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name)
1035 else
1036 @relation
1037 end
db045db @dhh Initial
dhh authored
1038 end
81737fc @jeremy r1613@asus: jeremy | 2005-07-03 07:04:53 -0700
jeremy authored
1039
3fc2d1e @jeremy Extract class-finder method from instantiate
jeremy authored
1040 def find_sti_class(type_name)
0238228 @tenderlove type_name should check for blank because people may have messed up da…
tenderlove authored
1041 if type_name.blank? || !columns_hash.include?(inheritance_column)
3fc2d1e @jeremy Extract class-finder method from instantiate
jeremy authored
1042 self
1043 else
1044 begin
0b73f2a @pixeltrix Optimize find_sti_class when store_full_sti_class is true
pixeltrix authored
1045 if store_full_sti_class
1046 ActiveSupport::Dependencies.constantize(type_name)
1047 else
1048 compute_type(type_name)
1049 end
3fc2d1e @jeremy Extract class-finder method from instantiate
jeremy authored
1050 rescue NameError
1051 raise SubclassNotFound,
1052 "The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " +
1053 "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " +
1054 "Please rename this column if you didn't intend it to be used for storing the inheritance class " +
1055 "or overwrite #{name}.inheritance_column to use another column for that information."
1056 end
1057 end
1058 end
1059
bed9179 @lifo Make scopes use relations under the hood
lifo authored
1060 def construct_finder_arel(options = {}, scope = nil)
e8c7f1a @spastorino unscoped has nothing so merging with a relation just returns the rela…
spastorino authored
1061 relation = options.is_a?(Hash) ? unscoped.apply_finder_options(options) : options
bed9179 @lifo Make scopes use relations under the hood
lifo authored
1062 relation = scope.merge(relation) if scope
6b67df7 @miloops Revert "Revert "Add readonly support for relations.""
miloops authored
1063 relation
19d2ff8 @miloops Calculations now use Arel to construct the query.
miloops authored
1064 end
1065
b7f1b36 @jonleighton Use Base#type_condition in JoinAssociation
jonleighton authored
1066 def type_condition(table = arel_table)
1067 sti_column = table[inheritance_column.to_sym]
62b084f @jonleighton Specify the STI type condition using SQL IN rather than a whole load …
jonleighton authored
1068 sti_names = ([self] + descendants).map { |model| model.sti_name }
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
1069
62b084f @jonleighton Specify the STI type condition using SQL IN rather than a whole load …
jonleighton authored
1070 sti_column.in(sti_names)
db045db @dhh Initial
dhh authored
1071 end
1072
1073 # Guesses the table name, but does not decorate it with prefix and suffix information.
def7460 @technoweenie Added Base.abstract_class? that marks which classes are not part of t…
technoweenie authored
1074 def undecorated_table_name(class_name = base_class.name)
3b0e1d9 @josh Prefer string core_ext inflector methods over directly accessing Infl…
josh authored
1075 table_name = class_name.to_s.demodulize.underscore
1076 table_name = table_name.pluralize if pluralize_table_names
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
1077 table_name
db045db @dhh Initial
dhh authored
1078 end
1079
4a8c880 @fxn refactors AR::Base#reset_table_name
fxn authored
1080 # Computes and returns a table name according to default conventions.
1081 def compute_table_name
1082 base = base_class
1083 if self == base
1084 # Nested classes are prefixed with singular parent table name.
1085 if parent < ActiveRecord::Base && !parent.abstract_class?
1086 contained = parent.table_name
1087 contained = contained.singularize if parent.pluralize_table_names
da6c7bd @spastorino Do not in place modify what table_name returns
spastorino authored
1088 contained += '_'
4a8c880 @fxn refactors AR::Base#reset_table_name
fxn authored
1089 end
1090 "#{full_table_name_prefix}#{contained}#{undecorated_table_name(name)}#{table_name_suffix}"
1091 else
1092 # STI subclasses always use their superclass' table.
1093 base.table_name
1094 end
1095 end
1096
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
1097 # Enables dynamic finders like <tt>User.find_by_user_name(user_name)</tt> and
db0e3e5 @neerajdotname Correcting the documentation which wrongly states that each dynamic f…
neerajdotname authored
1098 # <tt>User.scoped_by_user_name(user_name). Refer to Dynamic attribute-based finders
1099 # section at the top of this file for more detailed information.
2a30594 @technoweenie documentation project patches, closes #7342, #7319, #7316, #7190 [jer…
technoweenie authored
1100 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
1101 # It's even possible to use all the additional parameters to +find+. For example, the
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
1102 # full interface for +find_all_by_amount+ is actually <tt>find_all_by_amount(amount, options)</tt>.
4a1388a Define dynamic finders as real methods after first usage. Close #9317
Tobias Lütke authored
1103 #
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
1104 # Each dynamic finder using <tt>scoped_by_*</tt> is also defined in the class after it
b8d9d9c @neerajdotname updating documentation to ensure line does not exceed 100 columns
neerajdotname authored
1105 # is first invoked, so that future attempts to use it do not run through method_missing.
8a77c4a Fixed issue where block is not called on the very first invocation of…
Ken Miller authored
1106 def method_missing(method_id, *arguments, &block)
1ccca1b @sikachu Refactor the code a bit to reduce the duplication
sikachu authored
1107 if match = (DynamicFinderMatch.match(method_id) || DynamicScopeMatch.match(method_id))
143f5fb @joshsusser refactor dynamic finder name matching into its own class
joshsusser authored
1108 attribute_names = match.attribute_names
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many …
dhh authored
1109 super unless all_attributes_exists?(attribute_names)
6e69949 @sikachu Raise an ArgumentError if user passing less number of argument in the…
sikachu authored
1110 if arguments.size < attribute_names.size
1111 method_trace = "#{__FILE__}:#{__LINE__}:in `#{method_id}'"
1112 backtrace = [method_trace] + caller
1113 raise ArgumentError, "wrong number of arguments (#{arguments.size} for #{attribute_names.size})", backtrace
1114 end
1ccca1b @sikachu Refactor the code a bit to reduce the duplication
sikachu authored
1115 if match.respond_to?(:scope?) && match.scope?
13e00ce @spastorino fix stack trace lines on class_eval
spastorino authored
1116 self.class_eval <<-METHOD, __FILE__, __LINE__ + 1
7f444a3 @tenderlove roll up weird method to meta programmed method
tenderlove authored
1117 def self.#{method_id}(*args) # def self.scoped_by_user_name_and_password(*args)