Skip to content

HTTPS clone URL

Subversion checkout URL

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