Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

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