Skip to content

HTTPS clone URL

Subversion checkout URL

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