Skip to content

HTTPS clone URL

Subversion checkout URL

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