Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

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