Skip to content
Newer
Older
100755 2249 lines (2031 sloc) 99.1 KB
db045db @dhh Initial
dhh authored Nov 24, 2004
1 require 'yaml'
aabf909 @jeremy Correct reader method generation for primary key attribute: handle ca…
jeremy authored Nov 2, 2005
2 require 'set'
a15e02d @josevalim Unify benchmark APIs.
josevalim authored Oct 9, 2009
3 require 'active_support/benchmarkable'
f5d720f @jeremy Opt in to Dependencies
jeremy authored Apr 22, 2009
4 require 'active_support/dependencies'
5f222c5 @jeremy Remove 'core' fluff. Hookable ActiveSupport.load_all!
jeremy authored May 20, 2009
5 require 'active_support/time'
e8550ee @jeremy Cherry-pick core extensions
jeremy authored May 13, 2009
6 require 'active_support/core_ext/class/attribute_accessors'
7 require 'active_support/core_ext/class/delegating_attributes'
8 require 'active_support/core_ext/class/inheritable_attributes'
9 require 'active_support/core_ext/array/extract_options'
10 require 'active_support/core_ext/hash/deep_merge'
11 require 'active_support/core_ext/hash/indifferent_access'
12 require 'active_support/core_ext/hash/slice'
13 require 'active_support/core_ext/string/behavior'
f7b0a85 @jeremy Use Object#singleton_class instead of #metaclass. Prefer Ruby's choice.
jeremy authored Feb 25, 2010
14 require 'active_support/core_ext/object/singleton_class'
a7fd564 @lifo Add Model.select/group/order/limit/joins/conditions/preload/eager_loa…
lifo authored Dec 26, 2009
15 require 'active_support/core_ext/module/delegation'
105f9b8 @fxn adds missing requires for Object#duplicable?
fxn authored Mar 28, 2010
16 require 'active_support/core_ext/object/duplicable'
76f024a @fxn adds missing requires for Object#blank? and Object#present?
fxn authored Mar 28, 2010
17 require 'active_support/core_ext/object/blank'
39d6f9e @wycats Make many parts of Rails lazy. In order to facilitate this,
wycats authored Mar 7, 2010
18 require 'arel'
19 require 'active_record/errors'
db045db @dhh Initial
dhh authored Nov 24, 2004
20
21 module ActiveRecord #:nodoc:
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored Oct 11, 2005
22 # Active Record objects don't specify their attributes directly, but rather infer them from the table definition with
db045db @dhh Initial
dhh authored Nov 24, 2004
23 # which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change
24 # is instantly reflected in the 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 Jul 3, 2005
25 # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
26 #
db045db @dhh Initial
dhh authored Nov 24, 2004
27 # See the mapping rules in table_name and the full example in link:files/README.html for more insight.
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
28 #
db045db @dhh Initial
dhh authored Nov 24, 2004
29 # == Creation
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
30 #
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored Oct 11, 2005
31 # Active Records accept constructor parameters either in a hash or as a block. The hash method is especially useful when
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobS…
Marcel Molina authored Nov 8, 2007
32 # you're receiving the data from somewhere else, like an HTTP request. It works like this:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
33 #
0591c53 @dhh Made the dynamic finders use the new find API and updated the example…
dhh authored Apr 17, 2005
34 # user = User.new(:name => "David", :occupation => "Code Artist")
db045db @dhh Initial
dhh authored Nov 24, 2004
35 # user.name # => "David"
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
36 #
db045db @dhh Initial
dhh authored Nov 24, 2004
37 # You can also use block initialization:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
38 #
db045db @dhh Initial
dhh authored Nov 24, 2004
39 # user = User.new do |u|
40 # u.name = "David"
41 # u.occupation = "Code Artist"
42 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
43 #
db045db @dhh Initial
dhh authored Nov 24, 2004
44 # 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 Jul 3, 2005
45 #
db045db @dhh Initial
dhh authored Nov 24, 2004
46 # user = User.new
47 # user.name = "David"
48 # user.occupation = "Code Artist"
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
49 #
db045db @dhh Initial
dhh authored Nov 24, 2004
50 # == Conditions
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
51 #
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored Jun 3, 2006
52 # Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement.
db045db @dhh Initial
dhh authored Nov 24, 2004
53 # 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 Jun 3, 2006
54 # 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 Jan 10, 2007
55 # only equality and range is possible. Examples:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
56 #
48052d7 @jeremy to_xml fixes, features, and speedup. Closes #4989.
jeremy authored Jun 3, 2006
57 # class User < ActiveRecord::Base
db045db @dhh Initial
dhh authored Nov 24, 2004
58 # def self.authenticate_unsafely(user_name, password)
3dfa56c @dhh Updated all references to the old find_first and find_all to use the …
dhh authored Jun 26, 2005
59 # find(:first, :conditions => "user_name = '#{user_name}' AND password = '#{password}'")
db045db @dhh Initial
dhh authored Nov 24, 2004
60 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
61 #
db045db @dhh Initial
dhh authored Nov 24, 2004
62 # def self.authenticate_safely(user_name, password)
3dfa56c @dhh Updated all references to the old find_first and find_all to use the …
dhh authored Jun 26, 2005
63 # find(:first, :conditions => [ "user_name = ? AND password = ?", user_name, password ])
db045db @dhh Initial
dhh authored Nov 24, 2004
64 # end
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored Jun 3, 2006
65 #
66 # def self.authenticate_safely_simply(user_name, password)
67 # find(:first, :conditions => { :user_name => user_name, :password => password })
68 # end
db045db @dhh Initial
dhh authored Nov 24, 2004
69 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
70 #
2575b3b @dhh Added extra words of caution for guarding against SQL-injection attacks
dhh authored Dec 6, 2004
71 # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobS…
Marcel Molina authored Nov 8, 2007
72 # attacks if the <tt>user_name</tt> and +password+ parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored Dec 10, 2007
73 # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+ before inserting them in the query,
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored Jun 3, 2006
74 # which will ensure that an attacker can't escape the query and fake the login (or worse).
2575b3b @dhh Added extra words of caution for guarding against SQL-injection attacks
dhh authored Dec 6, 2004
75 #
5cd38ca @dhh Added documentation about named bind variables
dhh authored Mar 27, 2005
76 # When using multiple parameters in the conditions, it can easily become hard to read exactly what the fourth or fifth
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
77 # question mark is supposed to represent. In those cases, you can resort to named bind variables instead. That's done by replacing
5cd38ca @dhh Added documentation about named bind variables
dhh authored Mar 27, 2005
78 # the question marks with symbols and supplying a hash with values for the matching symbol keys:
79 #
a7e6e00 Documentation for find incorrectly omits the :conditions option from …
Marcel Molina authored Dec 5, 2007
80 # Company.find(:first, :conditions => [
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
81 # "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
5cd38ca @dhh Added documentation about named bind variables
dhh authored Mar 27, 2005
82 # { :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' }
83 # ])
84 #
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored Jun 3, 2006
85 # Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
86 # operator. For instance:
87 #
88 # Student.find(:all, :conditions => { :first_name => "Harvey", :status => 1 })
89 # Student.find(:all, :conditions => params[:student])
90 #
2876707 @jeremy Pass a range in :conditions to use the SQL BETWEEN operator. Closes #…
jeremy authored Jan 10, 2007
91 # A range may be used in the hash to use the SQL BETWEEN operator:
92 #
93 # Student.find(:all, :conditions => { :grade => 9..12 })
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored Jun 3, 2006
94 #
aa4af60 @lifo Improve documentation.
lifo authored Apr 5, 2008
95 # An array may be used in the hash to use the SQL IN operator:
96 #
97 # Student.find(:all, :conditions => { :grade => [9,11,12] })
98 #
e033b5d @lifo Merge docrails
lifo authored Jul 25, 2009
99 # When joining tables, nested hashes or keys written in the form 'table_name.column_name' can be used to qualify the table name of a
100 # particular condition. For instance:
101 #
102 # Student.find(:all, :conditions => { :schools => { :type => 'public' }}, :joins => :schools)
103 # Student.find(:all, :conditions => { 'schools.type' => 'public' }, :joins => :schools)
104 #
db045db @dhh Initial
dhh authored Nov 24, 2004
105 # == Overwriting default accessors
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
106 #
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobS…
Marcel Molina authored Nov 8, 2007
107 # All column values are automatically available through basic accessors on the Active Record object, but sometimes you
108 # want to specialize this behavior. This can be done by overwriting the default accessors (using the same
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
109 # name as the attribute) and calling <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually change things.
db045db @dhh Initial
dhh authored Nov 24, 2004
110 # Example:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
111 #
db045db @dhh Initial
dhh authored Nov 24, 2004
112 # class Song < ActiveRecord::Base
113 # # 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 Jul 3, 2005
114 #
db045db @dhh Initial
dhh authored Nov 24, 2004
115 # def length=(minutes)
64092de @fxn Improve documentation coverage and markup
fxn authored May 2, 2008
116 # write_attribute(:length, minutes.to_i * 60)
db045db @dhh Initial
dhh authored Nov 24, 2004
117 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
118 #
db045db @dhh Initial
dhh authored Nov 24, 2004
119 # def length
0591c53 @dhh Made the dynamic finders use the new find API and updated the example…
dhh authored Apr 17, 2005
120 # read_attribute(:length) / 60
db045db @dhh Initial
dhh authored Nov 24, 2004
121 # end
122 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
123 #
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
124 # You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt> instead of <tt>write_attribute(:attribute, value)</tt> and
125 # <tt>read_attribute(:attribute)</tt> as a shorter form.
0591c53 @dhh Made the dynamic finders use the new find API and updated the example…
dhh authored Apr 17, 2005
126 #
e4d845e Document automatically generated predicate methods for attributes. Cl…
Marcel Molina authored Dec 5, 2007
127 # == Attribute query methods
128 #
129 # In addition to the basic accessors, query methods are also automatically available on the Active Record object.
130 # Query methods allow you to test whether an attribute value is present.
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored Dec 10, 2007
131 #
e4d845e Document automatically generated predicate methods for attributes. Cl…
Marcel Molina authored Dec 5, 2007
132 # For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
133 # to determine whether the user has a name:
134 #
135 # user = User.new(:name => "David")
136 # user.name? # => true
137 #
138 # anonymous = User.new(:name => "")
139 # anonymous.name? # => false
140 #
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored Oct 11, 2005
141 # == Accessing attributes before they have been typecasted
4eab375 @dhh Finished polishing API docs
dhh authored Feb 23, 2005
142 #
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored Oct 11, 2005
143 # Sometimes you want to be able to read the raw attribute data without having the column-determined typecast run its course first.
dc4eec1 @lifo Merge docrails:
lifo authored May 9, 2008
144 # That can be done by using the <tt><attribute>_before_type_cast</tt> accessors that all attributes have. For example, if your Account model
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
145 # has a <tt>balance</tt> attribute, 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 Feb 23, 2005
146 #
147 # This is especially useful in validation situations where the user might supply a string for an integer field and you want to display
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored Oct 11, 2005
148 # the original string back in an error message. Accessing the attribute normally would typecast the string to 0, which isn't what you
4eab375 @dhh Finished polishing API docs
dhh authored Feb 23, 2005
149 # want.
150 #
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting obj…
dhh authored Jan 2, 2005
151 # == Dynamic attribute-based finders
152 #
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many …
dhh authored Nov 4, 2005
153 # Dynamic attribute-based finders are a cleaner way of getting (and/or creating) objects by simple queries without turning to SQL. They work by
6dc9173 @dhh Missing doc updates
dhh authored Sep 9, 2008
154 # appending the name of an attribute to <tt>find_by_</tt>, <tt>find_last_by_</tt>, or <tt>find_all_by_</tt>, so you get finders like <tt>Person.find_by_user_name</tt>,
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
155 # <tt>Person.find_all_by_last_name</tt>, and <tt>Payment.find_by_transaction_id</tt>. So instead of writing
a7e6e00 Documentation for find incorrectly omits the :conditions option from …
Marcel Molina authored Dec 5, 2007
156 # <tt>Person.find(:first, :conditions => ["user_name = ?", user_name])</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
157 # And instead of writing <tt>Person.find(:all, :conditions => ["last_name = ?", last_name])</tt>, you just do <tt>Person.find_all_by_last_name(last_name)</tt>.
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
158 #
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting obj…
dhh authored Jan 2, 2005
159 # It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like
160 # <tt>Person.find_by_user_name_and_password</tt> or even <tt>Payment.find_by_purchaser_and_state_and_country</tt>. So instead of writing
a7e6e00 Documentation for find incorrectly omits the :conditions option from …
Marcel Molina authored Dec 5, 2007
161 # <tt>Person.find(:first, :conditions => ["user_name = ? AND password = ?", user_name, password])</tt>, you just do
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting obj…
dhh authored Jan 2, 2005
162 # <tt>Person.find_by_user_name_and_password(user_name, password)</tt>.
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
163 #
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
164 # It's even possible to use all the additional parameters to find. For example, the full interface for <tt>Payment.find_all_by_amount</tt>
165 # is actually <tt>Payment.find_all_by_amount(amount, options)</tt>. And the full interface to <tt>Person.find_by_user_name</tt> is
64092de @fxn Improve documentation coverage and markup
fxn authored May 2, 2008
166 # actually <tt>Person.find_by_user_name(user_name, options)</tt>. So you could call <tt>Payment.find_all_by_amount(50, :order => "created_on")</tt>.
567392b @miloops Added find_last_by dynamic finder [status:committed #762]
miloops authored Sep 1, 2008
167 # Also you may call <tt>Payment.find_last_by_amount(amount, options)</tt> returning the last record matching that amount and options.
959f362 @dhh Added find_all style to the new dynamic finders
dhh authored Jan 2, 2005
168 #
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many …
dhh authored Nov 4, 2005
169 # The same dynamic finder style can be used to create the object if it doesn't already exist. This dynamic finder is called with
5c47ceb @NZKoz Typo fix in documentation from [9090] References #11422
NZKoz authored Mar 26, 2008
170 # <tt>find_or_create_by_</tt> and will return the object if it already exists and otherwise creates it, then returns it. Protected attributes won't be set unless they are given in a block. For example:
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many …
dhh authored Nov 4, 2005
171 #
172 # # No 'Summer' tag exists
173 # Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored Dec 10, 2007
174 #
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many …
dhh authored Nov 4, 2005
175 # # Now the 'Summer' tag does exist
176 # Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
177 #
c10b225 @dhh Fixed that ActiveRecord#Base.find_or_create/initialize would not hono…
dhh authored Mar 25, 2008
178 # # Now 'Bob' exist and is an 'admin'
179 # User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }
180 #
0432d15 @lifo Merge with docrails.
lifo authored Jul 16, 2008
181 # Use the <tt>find_or_initialize_by_</tt> finder if you want to return a new record without saving it first. Protected attributes won't be set unless they are given in a block. For example:
d19e464 @sstephenson Added find_or_initialize_by_X which works like find_or_create_by_X bu…
sstephenson authored Jun 20, 2006
182 #
183 # # No 'Winter' tag exists
184 # winter = Tag.find_or_initialize_by_name("Winter")
85fbb22 @dhh Backed out of new_record? to new? transformation as it would screw up…
dhh authored Sep 5, 2006
185 # winter.new_record? # true
d19e464 @sstephenson Added find_or_initialize_by_X which works like find_or_create_by_X bu…
sstephenson authored Jun 20, 2006
186 #
14cc8d2 @jeremy find_or_create_by_* takes a hash so you can create with more attribut…
jeremy authored Mar 14, 2007
187 # To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of
188 # a list of parameters. For example:
189 #
190 # Tag.find_or_create_by_name(:name => "rails", :creator => current_user)
191 #
192 # That will either find an existing tag named "rails", or create a new one while setting the user that created it.
193 #
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored Feb 7, 2005
194 # == 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 Jul 3, 2005
195 #
196 # Active Record can serialize any object in text columns using YAML. To do so, you must specify this with a call to the class method +serialize+.
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored Oct 11, 2005
197 # This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work. Example:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
198 #
db045db @dhh Initial
dhh authored Nov 24, 2004
199 # class User < ActiveRecord::Base
200 # serialize :preferences
201 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
202 #
ca2eb16 Fix syntax error in documentation. Closes #4679. [mislav@nippur.irb.hr]
Marcel Molina authored Apr 26, 2006
203 # user = User.create(:preferences => { "background" => "black", "display" => large })
db045db @dhh Initial
dhh authored Nov 24, 2004
204 # User.find(user.id).preferences # => { "background" => "black", "display" => large }
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
205 #
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored Oct 11, 2005
206 # You can also specify a class option as the second parameter that'll raise an exception if a serialized object is retrieved as a
39e1ac6 @lifo Merge docrails
lifo authored Jan 18, 2009
207 # descendant of a class not in the hierarchy. Example:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
208 #
db045db @dhh Initial
dhh authored Nov 24, 2004
209 # class User < ActiveRecord::Base
66f44e6 @dhh Updated documentation for serialize
dhh authored Jan 25, 2005
210 # serialize :preferences, Hash
db045db @dhh Initial
dhh authored Nov 24, 2004
211 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
212 #
0591c53 @dhh Made the dynamic finders use the new find API and updated the example…
dhh authored Apr 17, 2005
213 # user = User.create(:preferences => %w( one two three ))
db045db @dhh Initial
dhh authored Nov 24, 2004
214 # User.find(user.id).preferences # raises SerializationTypeMismatch
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
215 #
db045db @dhh Initial
dhh authored Nov 24, 2004
216 # == Single table inheritance
217 #
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobS…
Marcel Molina authored Nov 8, 2007
218 # Active Record allows inheritance by storing the name of the class in a column that by default is named "type" (can be changed
db045db @dhh Initial
dhh authored Nov 24, 2004
219 # by overwriting <tt>Base.inheritance_column</tt>). This means that an inheritance looking like this:
220 #
221 # class Company < ActiveRecord::Base; end
222 # class Firm < Company; end
223 # class Client < Company; end
224 # class PriorityClient < Client; end
225 #
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
226 # When you do <tt>Firm.create(:name => "37signals")</tt>, this record will be saved in the companies table with type = "Firm". You can then
227 # fetch this row again using <tt>Company.find(:first, "name = '37signals'")</tt> and it will return a Firm object.
db045db @dhh Initial
dhh authored Nov 24, 2004
228 #
f033833 @dhh Improving documentation...
dhh authored Dec 16, 2004
229 # If you don't have a type column defined in your table, single-table inheritance won't be triggered. In that case, it'll work just
230 # like normal subclasses with no special magic for differentiating between them or reloading the right type with find.
231 #
db045db @dhh Initial
dhh authored Nov 24, 2004
232 # Note, all the attributes for all the cases are kept in the same table. Read more:
233 # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
234 #
db045db @dhh Initial
dhh authored Nov 24, 2004
235 # == Connection to multiple databases in different models
236 #
237 # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection.
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
238 # All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection.
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
239 # For example, if Course is an ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
240 # and Course and all of its subclasses will use this connection instead.
db045db @dhh Initial
dhh authored Nov 24, 2004
241 #
242 # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is
243 # requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool.
244 #
245 # == Exceptions
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
246 #
dc4eec1 @lifo Merge docrails:
lifo authored May 9, 2008
247 # * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record.
248 # * AdapterNotSpecified - The configuration hash used in <tt>establish_connection</tt> didn't include an
db045db @dhh Initial
dhh authored Nov 24, 2004
249 # <tt>:adapter</tt> key.
dc4eec1 @lifo Merge docrails:
lifo authored May 9, 2008
250 # * AdapterNotFound - The <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a non-existent adapter
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
251 # (or a bad spelling of an existing one).
dc4eec1 @lifo Merge docrails:
lifo authored May 9, 2008
252 # * AssociationTypeMismatch - The object assigned to the association wasn't of the type specified in the association definition.
253 # * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
254 # * ConnectionNotEstablished+ - No connection has been established. Use <tt>establish_connection</tt> before querying.
255 # * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
256 # or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
257 # nothing was found, please check its documentation for further details.
258 # * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
259 # * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the
260 # <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of AttributeAssignmentError
d2fefbe @dhh Added MultiparameterAssignmentErrors and AttributeAssignmentError exc…
dhh authored Mar 6, 2005
261 # objects that should be inspected to determine which attributes triggered the errors.
dc4eec1 @lifo Merge docrails:
lifo authored May 9, 2008
262 # * AttributeAssignmentError - An error occurred while doing a mass assignment through the <tt>attributes=</tt> method.
d2fefbe @dhh Added MultiparameterAssignmentErrors and AttributeAssignmentError exc…
dhh authored Mar 6, 2005
263 # You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error.
5707027 @dhh Added better exception error when unknown column types are used with …
dhh authored Sep 11, 2005
264 #
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
265 # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
dc4eec1 @lifo Merge docrails:
lifo authored May 9, 2008
266 # 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 Nov 24, 2004
267 # instances in the current object space.
268 class Base
0905396 @miloops construct_finder_sql now use Arel
miloops authored Apr 24, 2009
269 ##
dbbae5e @lifo Merge with docrails
lifo authored Dec 7, 2008
270 # :singleton-method:
db045db @dhh Initial
dhh authored Nov 24, 2004
271 # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed
272 # on to any new database connections made and which can be retrieved on both a class and instance level by calling +logger+.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7401
technoweenie authored Jan 28, 2007
273 cattr_accessor :logger, :instance_writer => false
e694114 @jeremy Deprecation: removed Reloadable.
jeremy authored Sep 14, 2007
274
db045db @dhh Initial
dhh authored Nov 24, 2004
275 def self.inherited(child) #:nodoc:
276 @@subclasses[self] ||= []
277 @@subclasses[self] << child
278 super
279 end
e694114 @jeremy Deprecation: removed Reloadable.
jeremy authored Sep 14, 2007
280
fed7d33 @dhh Fixed documentation
dhh authored Mar 28, 2006
281 def self.reset_subclasses #:nodoc:
bfbf6bb @jamis Allow ARStore::Session to indicate that it should not be reloaded in …
jamis authored Oct 15, 2005
282 nonreloadables = []
e7f61ea @jamis squash the memleak in dev mode finally (fingers crossed, here)
jamis authored Oct 15, 2005
283 subclasses.each do |klass|
c08547d @josh Namespace Inflector, Dependencies, OrderedOptions, and TimeZone under…
josh authored Jun 3, 2008
284 unless ActiveSupport::Dependencies.autoloaded? klass
bfbf6bb @jamis Allow ARStore::Session to indicate that it should not be reloaded in …
jamis authored Oct 15, 2005
285 nonreloadables << klass
286 next
287 end
e7f61ea @jamis squash the memleak in dev mode finally (fingers crossed, here)
jamis authored Oct 15, 2005
288 klass.instance_variables.each { |var| klass.send(:remove_instance_variable, var) }
289 klass.instance_methods(false).each { |m| klass.send :undef_method, m }
290 end
bfbf6bb @jamis Allow ARStore::Session to indicate that it should not be reloaded in …
jamis authored Oct 15, 2005
291 @@subclasses = {}
292 nonreloadables.each { |klass| (@@subclasses[klass.superclass] ||= []) << klass }
3c0129a @dhh Fixed memory leak with Active Record classes when Dependencies.mechan…
dhh authored Sep 20, 2005
293 end
294
db045db @dhh Initial
dhh authored Nov 24, 2004
295 @@subclasses = {}
c3aa2bc @Manfred Ensure nested with_scope merges conditions inside out [#2193 state:re…
Manfred authored Mar 10, 2009
296
dbbae5e @lifo Merge with docrails
lifo authored Dec 7, 2008
297 ##
298 # :singleton-method:
a293278 @lifo Merge docrails
lifo authored Oct 5, 2008
299 # Contains the database configuration - as is typically stored in config/database.yml -
300 # as a Hash.
301 #
302 # For example, the following database.yml...
0905396 @miloops construct_finder_sql now use Arel
miloops authored Apr 25, 2009
303 #
a293278 @lifo Merge docrails
lifo authored Oct 5, 2008
304 # development:
305 # adapter: sqlite3
306 # database: db/development.sqlite3
0905396 @miloops construct_finder_sql now use Arel
miloops authored Apr 25, 2009
307 #
a293278 @lifo Merge docrails
lifo authored Oct 5, 2008
308 # production:
309 # adapter: sqlite3
310 # database: db/production.sqlite3
311 #
312 # ...would result in ActiveRecord::Base.configurations to look like this:
313 #
314 # {
315 # 'development' => {
316 # 'adapter' => 'sqlite3',
317 # 'database' => 'db/development.sqlite3'
318 # },
319 # 'production' => {
320 # 'adapter' => 'sqlite3',
321 # 'database' => 'db/production.sqlite3'
322 # }
323 # }
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7401
technoweenie authored Jan 28, 2007
324 cattr_accessor :configurations, :instance_writer => false
c4a3634 @jeremy Corrected @@configurations typo. #1410 [david@ruppconsulting.com]
jeremy authored Jun 12, 2005
325 @@configurations = {}
326
dbbae5e @lifo Merge with docrails
lifo authored Dec 7, 2008
327 ##
328 # :singleton-method:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
329 # Accessor for the prefix type that will be prepended to every primary key column name. The options are :table_name and
db045db @dhh Initial
dhh authored Nov 24, 2004
330 # :table_name_with_underscore. If the first is specified, the Product class will look for "productid" instead of "id" as
331 # the primary column. If the 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 Jul 3, 2005
332 # that this is a global setting for all Active Records.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7401
technoweenie authored Jan 28, 2007
333 cattr_accessor :primary_key_prefix_type, :instance_writer => false
db045db @dhh Initial
dhh authored Nov 24, 2004
334 @@primary_key_prefix_type = nil
335
dbbae5e @lifo Merge with docrails
lifo authored Dec 7, 2008
336 ##
337 # :singleton-method:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
338 # Accessor for the name of the prefix string to prepend to every table name. So if set to "basecamp_", all
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored Feb 7, 2005
339 # table names will be named like "basecamp_projects", "basecamp_people", etc. This is a convenient way of creating a namespace
db045db @dhh Initial
dhh authored Nov 24, 2004
340 # for tables in a shared database. By default, the prefix is the empty string.
67d1cec @pixeltrix Add the ability to specify table_name_prefix on individual modules
pixeltrix authored Feb 22, 2010
341 #
342 # If you are organising your models within modules you can add a prefix to the models within a namespace by defining
343 # a singleton method in the parent module called table_name_prefix which returns your chosen prefix.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7401
technoweenie authored Jan 28, 2007
344 cattr_accessor :table_name_prefix, :instance_writer => false
db045db @dhh Initial
dhh authored Nov 24, 2004
345 @@table_name_prefix = ""
346
dbbae5e @lifo Merge with docrails
lifo authored Dec 7, 2008
347 ##
348 # :singleton-method:
db045db @dhh Initial
dhh authored Nov 24, 2004
349 # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
350 # "people_basecamp"). By default, the suffix is the empty string.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7401
technoweenie authored Jan 28, 2007
351 cattr_accessor :table_name_suffix, :instance_writer => false
db045db @dhh Initial
dhh authored Nov 24, 2004
352 @@table_name_suffix = ""
353
dbbae5e @lifo Merge with docrails
lifo authored Dec 7, 2008
354 ##
355 # :singleton-method:
84a14f2 @jeremy Raise ProtectedAttributeAssignmentError in development and test envir…
jeremy authored Oct 7, 2007
356 # Indicates whether table names should be the pluralized versions of the corresponding class names.
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
357 # 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 Nov 24, 2004
358 # See table_name for the full rules on table/class naming. This is true, by default.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7401
technoweenie authored Jan 28, 2007
359 cattr_accessor :pluralize_table_names, :instance_writer => false
db045db @dhh Initial
dhh authored Nov 24, 2004
360 @@pluralize_table_names = true
361
dbbae5e @lifo Merge with docrails
lifo authored Dec 7, 2008
362 ##
363 # :singleton-method:
60de8c1 @dhh Added Base.default_timezone accessor that determines whether to use T…
dhh authored Dec 28, 2004
364 # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates and times from the database.
365 # This is set to :local by default.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7401
technoweenie authored Jan 28, 2007
366 cattr_accessor :default_timezone, :instance_writer => false
60de8c1 @dhh Added Base.default_timezone accessor that determines whether to use T…
dhh authored Dec 28, 2004
367 @@default_timezone = :local
d8641ca @jeremy CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. M…
jeremy authored Mar 1, 2006
368
dbbae5e @lifo Merge with docrails
lifo authored Dec 7, 2008
369 ##
370 # :singleton-method:
24c3599 @sstephenson Support using different database adapters for development and test wi…
sstephenson authored Oct 13, 2005
371 # Specifies the format to use when dumping the database schema with Rails'
372 # Rakefile. If :sql, the schema is dumped as (potentially database-
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored Dec 10, 2007
373 # 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 Oct 13, 2005
374 # ActiveRecord::Schema file which can be loaded into any database that
375 # supports migrations. Use :ruby if you want to have different database
376 # adapters for, e.g., your development and test environments.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7401
technoweenie authored Jan 28, 2007
377 cattr_accessor :schema_format , :instance_writer => false
660952e @dhh CHANGED DEFAULT: ActiveRecord::Base.schema_format is now :ruby by def…
dhh authored Feb 27, 2006
378 @@schema_format = :ruby
3b0e1d9 @josh Prefer string core_ext inflector methods over directly accessing Infl…
josh authored May 14, 2008
379
dbbae5e @lifo Merge with docrails
lifo authored Dec 7, 2008
380 ##
381 # :singleton-method:
bbab639 @nikz Set config.active_record.timestamped_migrations = false to have migra…
nikz authored Jul 17, 2008
382 # Specify whether or not to use timestamps for migration numbers
383 cattr_accessor :timestamped_migrations , :instance_writer => false
384 @@timestamped_migrations = true
385
bca8751 @divoxx Add ActiveRecord option to store the full class name on STI's type co…
divoxx authored Apr 11, 2008
386 # Determine whether to store the full constant name including namespace when using STI
387 superclass_delegating_accessor :store_full_sti_class
1459c8c @dhh Changed ActiveRecord::Base.store_full_sti_class to be true by default…
dhh authored Jan 3, 2010
388 self.store_full_sti_class = true
3b0e1d9 @josh Prefer string core_ext inflector methods over directly accessing Infl…
josh authored May 14, 2008
389
2530d0e @lifo Added default_scope to Base [#1381 state:committed] (Paweł Kondzior)
lifo authored Nov 16, 2008
390 # Stores the default scope for the class
391 class_inheritable_accessor :default_scoping, :instance_writer => false
392 self.default_scoping = []
393
db045db @dhh Initial
dhh authored Nov 24, 2004
394 class << self # Class methods
8d78a82 @josevalim Deprecate ActiveRecord::Base.colorize_logging.
josevalim authored Jan 12, 2010
395 def colorize_logging(*args)
396 ActiveSupport::Deprecation.warn "ActiveRecord::Base.colorize_logging and " <<
39d6f9e @wycats Make many parts of Rails lazy. In order to facilitate this,
wycats authored Mar 7, 2010
397 "config.active_record.colorize_logging are deprecated. Please use " <<
f0523f7 @sikachu Rename Rails::Subscriber to Rails::LogSubscriber
sikachu authored Feb 15, 2010
398 "Rails::LogSubscriber.colorize_logging or config.colorize_logging instead", caller
8d78a82 @josevalim Deprecate ActiveRecord::Base.colorize_logging.
josevalim authored Jan 12, 2010
399 end
400 alias :colorize_logging= :colorize_logging
401
8d31c9f @lifo Move update and update_all to Relation
lifo authored Jan 20, 2010
402 delegate :find, :first, :last, :all, :destroy, :destroy_all, :exists?, :delete, :delete_all, :update, :update_all, :to => :scoped
dc3cc6c @lifo Move batch finders to Relation
lifo authored Feb 12, 2010
403 delegate :find_each, :find_in_batches, :to => :scoped
6f5f23a @lifo Add Relation#includes to be an equivalent of current finder option :i…
lifo authored Jan 3, 2010
404 delegate :select, :group, :order, :limit, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :to => :scoped
9465b84 @lifo Rename CalculationMethods to Calculations and get rid of the old Calc…
lifo authored Jan 19, 2010
405 delegate :count, :average, :minimum, :maximum, :sum, :calculate, :to => :scoped
a7fd564 @lifo Add Model.select/group/order/limit/joins/conditions/preload/eager_loa…
lifo authored Dec 25, 2009
406
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
407 # 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 Dec 10, 2007
408 # be returned as an array with columns requested encapsulated as attributes of the model you call
a293278 @lifo Merge docrails
lifo authored Oct 5, 2008
409 # this method from. If you call <tt>Product.find_by_sql</tt> then the results will be returned in
410 # 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 Dec 5, 2007
411 #
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored Dec 10, 2007
412 # If you call a complicated SQL query which spans multiple tables the columns specified by the
413 # 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 Dec 5, 2007
414 # table.
415 #
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
416 # The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored Dec 10, 2007
417 # no database agnostic conversions performed. This should be a last resort because using, for example,
418 # MySQL specific terms will lock you to using that particular database engine or require you to
a293278 @lifo Merge docrails
lifo authored Oct 5, 2008
419 # change your call if you switch engines.
edf32ce More complete documentation for find_by_sql. Closes #7912 [fearoffish]
Marcel Molina authored Dec 5, 2007
420 #
421 # ==== Examples
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
422 # # A simple SQL query spanning multiple tables
edf32ce More complete documentation for find_by_sql. Closes #7912 [fearoffish]
Marcel Molina authored Dec 5, 2007
423 # Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
424 # > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
425 #
426 # # You can use the same string replacement techniques as you can with ActiveRecord#find
427 # Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
428 # > [#<Post:0x36bff9c @attributes={"first_name"=>"The Cheap Man Buys Twice"}>, ...]
db045db @dhh Initial
dhh authored Nov 24, 2004
429 def find_by_sql(sql)
6e3d2a7 @jeremy Revert "Performance: freeze cached rows instead of duping"
jeremy authored Aug 21, 2008
430 connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) }
db045db @dhh Initial
dhh authored Nov 24, 2004
431 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
432
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored Dec 10, 2007
433 # 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 Dec 5, 2007
434 # The resulting object is returned whether the object was saved successfully to the database or not.
435 #
436 # The +attributes+ parameter can be either be a Hash or an Array of Hashes. These Hashes describe the
437 # attributes on the objects that are to be created.
438 #
439 # ==== Examples
440 # # Create a single new object
441 # User.create(:first_name => 'Jamie')
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new alrea…
dhh authored Apr 30, 2008
442 #
a23bea7 Document API for create's attributes parameter and provide examples. …
Marcel Molina authored Dec 5, 2007
443 # # Create an Array of new objects
dc4eec1 @lifo Merge docrails:
lifo authored May 9, 2008
444 # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new alrea…
dhh authored May 1, 2008
445 #
446 # # Create a single object and pass it into a block to set other attributes.
447 # User.create(:first_name => 'Jamie') do |u|
448 # u.is_admin = false
449 # end
450 #
451 # # Creating an Array of new objects using a block, where the block is executed for each object:
dc4eec1 @lifo Merge docrails:
lifo authored May 9, 2008
452 # 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 May 1, 2008
453 # u.is_admin = false
3b0e1d9 @josh Prefer string core_ext inflector methods over directly accessing Infl…
josh authored May 14, 2008
454 # end
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new alrea…
dhh authored May 1, 2008
455 def create(attributes = nil, &block)
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#…
dhh authored Jan 25, 2005
456 if attributes.is_a?(Array)
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new alrea…
dhh authored May 1, 2008
457 attributes.collect { |attr| create(attr, &block) }
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#…
dhh authored Jan 25, 2005
458 else
459 object = new(attributes)
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new alrea…
dhh authored May 1, 2008
460 yield(object) if block_given?
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#…
dhh authored Jan 25, 2005
461 object.save
462 object
463 end
db045db @dhh Initial
dhh authored Nov 24, 2004
464 end
465
466 # 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 Dec 10, 2007
467 # The use of this method should be restricted to complicated SQL queries that can't be executed
ee614d6 Add documentation caveat about when to use count_by_sql. Closes #8090.…
Marcel Molina authored May 6, 2007
468 # using the ActiveRecord::Calculations class methods. Look into those before using this.
469 #
a293278 @lifo Merge docrails
lifo authored Oct 5, 2008
470 # ==== Parameters
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored Dec 10, 2007
471 #
dc4eec1 @lifo Merge docrails:
lifo authored May 9, 2008
472 # * +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 May 6, 2007
473 #
474 # ==== Examples
475 #
e17bf81 @jamis Fix typo in count_by_sql documentation #1969 [Alexey Verkhovsky]
jamis authored Aug 14, 2005
476 # Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
db045db @dhh Initial
dhh authored Nov 24, 2004
477 def count_by_sql(sql)
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in r…
dhh authored Dec 7, 2004
478 sql = sanitize_conditions(sql)
caaf40d @dhh Added AbstractAdapter#select_value and AbstractAdapter#select_values …
dhh authored Sep 24, 2005
479 connection.select_value(sql, "#{name} Count").to_i
db045db @dhh Initial
dhh authored Nov 24, 2004
480 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
481
3239589 @gtd Replace reset_counter_cache with reset_counters that has API inline w…
gtd authored Dec 2, 2009
482 # Resets one or more counter caches to their correct value using an SQL
483 # count query. This is useful when adding new counter caches, or if the
484 # counter has been corrupted or modified directly by SQL.
50c28e7 @hardbap Implement ActiveRecord#reset_counter_cache
hardbap authored May 20, 2009
485 #
486 # ==== Parameters
487 #
3239589 @gtd Replace reset_counter_cache with reset_counters that has API inline w…
gtd authored Dec 2, 2009
488 # * +id+ - The id of the object you wish to reset a counter on.
489 # * +counters+ - One or more counter names to reset
50c28e7 @hardbap Implement ActiveRecord#reset_counter_cache
hardbap authored May 20, 2009
490 #
491 # ==== Examples
3239589 @gtd Replace reset_counter_cache with reset_counters that has API inline w…
gtd authored Dec 2, 2009
492 #
493 # # For Post with id #1 records reset the comments_count
494 # Post.reset_counters(1, :comments)
495 def reset_counters(id, *counters)
496 object = find(id)
497 counters.each do |association|
498 child_class = reflect_on_association(association).klass
499 counter_name = child_class.reflect_on_association(self.name.downcase.to_sym).counter_cache_column
50c28e7 @hardbap Implement ActiveRecord#reset_counter_cache
hardbap authored May 20, 2009
500
501 connection.update("UPDATE #{quoted_table_name} SET #{connection.quote_column_name(counter_name)} = #{object.send(association).count} WHERE #{connection.quote_column_name(primary_key)} = #{quote_value(object.id)}", "#{name} UPDATE")
502 end
503 end
504
8375237 @jamis Made increment_counter/decrement_counter play nicely with optimistic …
jamis authored Feb 7, 2007
505 # A generic "counter updater" implementation, intended primarily to be
506 # used by increment_counter and decrement_counter, but which may also
507 # be useful on its own. It simply does a direct SQL update for the record
508 # with the given ID, altering the given hash of counters by the amount
509 # given by the corresponding value:
510 #
a293278 @lifo Merge docrails
lifo authored Oct 5, 2008
511 # ==== Parameters
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored Dec 10, 2007
512 #
7487196 @lifo Add array id support to Model.update_counters. [#1254 state:resolved]…
lifo authored Jan 28, 2009
513 # * +id+ - The id of the object you wish to update a counter on or an Array of ids.
dc4eec1 @lifo Merge docrails:
lifo authored May 9, 2008
514 # * +counters+ - An Array of Hashes containing the names of the fields
515 # to update as keys and the amount to update the field by as values.
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored Dec 10, 2007
516 #
6bd7d30 Document options for update_counters. Closes #8091 [fearoffish]
Marcel Molina authored Dec 5, 2007
517 # ==== Examples
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored Dec 10, 2007
518 #
519 # # For the Post with id of 5, decrement the comment_count by 1, and
6bd7d30 Document options for update_counters. Closes #8091 [fearoffish]
Marcel Molina authored Dec 5, 2007
520 # # increment the action_count by 1
8375237 @jamis Made increment_counter/decrement_counter play nicely with optimistic …
jamis authored Feb 7, 2007
521 # Post.update_counters 5, :comment_count => -1, :action_count => 1
6bd7d30 Document options for update_counters. Closes #8091 [fearoffish]
Marcel Molina authored Dec 5, 2007
522 # # Executes the following SQL:
8375237 @jamis Made increment_counter/decrement_counter play nicely with optimistic …
jamis authored Feb 7, 2007
523 # # UPDATE posts
524 # # SET comment_count = comment_count - 1,
525 # # action_count = action_count + 1
526 # # WHERE id = 5
7487196 @lifo Add array id support to Model.update_counters. [#1254 state:resolved]…
lifo authored Jan 28, 2009
527 #
528 # # For the Posts with id of 10 and 15, increment the comment_count by 1
529 # Post.update_counters [10, 15], :comment_count => 1
530 # # Executes the following SQL:
531 # # UPDATE posts
532 # # SET comment_count = comment_count + 1,
533 # # WHERE id IN (10, 15)
8375237 @jamis Made increment_counter/decrement_counter play nicely with optimistic …
jamis authored Feb 7, 2007
534 def update_counters(id, counters)
535 updates = counters.inject([]) { |list, (counter_name, increment)|
536 sign = increment < 0 ? "-" : "+"
459e581 @miloops update_counters should update nil values.
miloops authored Jun 26, 2008
537 list << "#{connection.quote_column_name(counter_name)} = COALESCE(#{connection.quote_column_name(counter_name)}, 0) #{sign} #{increment.abs}"
8375237 @jamis Made increment_counter/decrement_counter play nicely with optimistic …
jamis authored Feb 7, 2007
538 }.join(", ")
7487196 @lifo Add array id support to Model.update_counters. [#1254 state:resolved]…
lifo authored Jan 28, 2009
539
540 if id.is_a?(Array)
541 ids_list = id.map {|i| quote_value(i)}.join(', ')
542 condition = "IN (#{ids_list})"
543 else
544 condition = "= #{quote_value(id)}"
545 end
546
547 update_all(updates, "#{connection.quote_column_name(primary_key)} #{condition}")
8375237 @jamis Made increment_counter/decrement_counter play nicely with optimistic …
jamis authored Feb 7, 2007
548 end
549
15dc567 Also add documentation enhancements for increment_counter. Closes #8092
Marcel Molina authored May 6, 2007
550 # Increment a number field by one, usually representing a count.
551 #
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored Dec 10, 2007
552 # This is used for caching aggregate values, so that they don't need to be computed every time.
553 # For example, a DiscussionBoard may cache post_count and comment_count otherwise every time the board is
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobS…
Marcel Molina authored Nov 8, 2007
554 # shown it would have to run an SQL query to find how many posts and comments there are.
15dc567 Also add documentation enhancements for increment_counter. Closes #8092
Marcel Molina authored May 6, 2007
555 #
a293278 @lifo Merge docrails
lifo authored Oct 5, 2008
556 # ==== Parameters
15dc567 Also add documentation enhancements for increment_counter. Closes #8092
Marcel Molina authored May 6, 2007
557 #
dc4eec1 @lifo Merge docrails:
lifo authored May 9, 2008
558 # * +counter_name+ - The name of the field that should be incremented.
559 # * +id+ - The id of the object that should be incremented.
15dc567 Also add documentation enhancements for increment_counter. Closes #8092
Marcel Molina authored May 6, 2007
560 #
561 # ==== Examples
562 #
563 # # Increment the post_count column for the record with an id of 5
564 # DiscussionBoard.increment_counter(:post_count, 5)
db045db @dhh Initial
dhh authored Nov 24, 2004
565 def increment_counter(counter_name, id)
8375237 @jamis Made increment_counter/decrement_counter play nicely with optimistic …
jamis authored Feb 7, 2007
566 update_counters(id, counter_name => 1)
db045db @dhh Initial
dhh authored Nov 24, 2004
567 end
568
5bd3570 Enhance documentation for decrement_counter. Closes #8093. [fearoffish]
Marcel Molina authored May 6, 2007
569 # Decrement a number field by one, usually representing a count.
570 #
571 # This works the same as increment_counter but reduces the column value by 1 instead of increasing it.
572 #
a293278 @lifo Merge docrails
lifo authored Oct 5, 2008
573 # ==== Parameters
5bd3570 Enhance documentation for decrement_counter. Closes #8093. [fearoffish]
Marcel Molina authored May 6, 2007
574 #
dc4eec1 @lifo Merge docrails:
lifo authored May 9, 2008
575 # * +counter_name+ - The name of the field that should be decremented.
576 # * +id+ - The id of the object that should be decremented.
5bd3570 Enhance documentation for decrement_counter. Closes #8093. [fearoffish]
Marcel Molina authored May 6, 2007
577 #
578 # ==== Examples
579 #
580 # # Decrement the post_count column for the record with an id of 5
581 # DiscussionBoard.decrement_counter(:post_count, 5)
db045db @dhh Initial
dhh authored Nov 24, 2004
582 def decrement_counter(counter_name, id)
8375237 @jamis Made increment_counter/decrement_counter play nicely with optimistic …
jamis authored Feb 7, 2007
583 update_counters(id, counter_name => -1)
db045db @dhh Initial
dhh authored Nov 24, 2004
584 end
585
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
586 # Attributes named in this macro are protected from mass-assignment,
587 # such as <tt>new(attributes)</tt>,
588 # <tt>update_attributes(attributes)</tt>, or
589 # <tt>attributes=(attributes)</tt>.
590 #
591 # Mass-assignment to these attributes will simply be ignored, to assign
592 # to them you can use direct writer methods. This is meant to protect
593 # sensitive attributes from being overwritten by malicious users
594 # tampering with URLs or forms.
db045db @dhh Initial
dhh authored Nov 24, 2004
595 #
596 # class Customer < ActiveRecord::Base
597 # attr_protected :credit_rating
598 # end
599 #
600 # customer = Customer.new("name" => David, "credit_rating" => "Excellent")
601 # customer.credit_rating # => nil
602 # customer.attributes = { "description" => "Jolly fellow", "credit_rating" => "Superb" }
603 # customer.credit_rating # => nil
604 #
605 # customer.credit_rating = "Average"
606 # customer.credit_rating # => "Average"
d761ac4 Add docs explaining how to protect all attributes using attr_accessib…
Marcel Molina authored Oct 26, 2007
607 #
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
608 # To start from an all-closed default and enable attributes as needed,
609 # have a look at +attr_accessible+.
e033b5d @lifo Merge docrails
lifo authored Jul 25, 2009
610 #
611 # If the access logic of your application is richer you can use <tt>Hash#except</tt>
612 # or <tt>Hash#slice</tt> to sanitize the hash of parameters before they are
613 # passed to Active Record.
31c8353 @miloops Don't use local vars before testing its conditional.
miloops authored Aug 3, 2009
614 #
e033b5d @lifo Merge docrails
lifo authored Jul 25, 2009
615 # For example, it could be the case that the list of protected attributes
616 # for a given model depends on the role of the user:
617 #
618 # # Assumes plan_id is not protected because it depends on the role.
619 # params[:account] = params[:account].except(:plan_id) unless admin?
620 # @account.update_attributes(params[:account])
621 #
622 # Note that +attr_protected+ is still applied to the received hash. Thus,
623 # with this technique you can at most _extend_ the list of protected
624 # attributes for a particular mass-assignment call.
db045db @dhh Initial
dhh authored Nov 24, 2004
625 def attr_protected(*attributes)
b6bac73 Merge commit 'origin/master'
Yehuda Katz + Carl Lerche authored May 14, 2009
626 write_inheritable_attribute(:attr_protected, Set.new(attributes.map {|a| a.to_s}) + (protected_attributes || []))
db045db @dhh Initial
dhh authored Nov 24, 2004
627 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
628
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored Feb 7, 2005
629 # Returns an array of all the attributes that have been protected from mass-assignment.
db045db @dhh Initial
dhh authored Nov 24, 2004
630 def protected_attributes # :nodoc:
288e947 @clemens Some performance goodness for inheritable attributes.
clemens authored Sep 2, 2008
631 read_inheritable_attribute(:attr_protected)
db045db @dhh Initial
dhh authored Nov 24, 2004
632 end
633
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
634 # Specifies a white list of model attributes that can be set via
635 # mass-assignment, such as <tt>new(attributes)</tt>,
636 # <tt>update_attributes(attributes)</tt>, or
637 # <tt>attributes=(attributes)</tt>
f770b82 Enhance explanation with more examples for attr_accessible macro. Clo…
Marcel Molina authored Nov 6, 2007
638 #
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
639 # This is the opposite of the +attr_protected+ macro: Mass-assignment
640 # will only set attributes in this list, to assign to the rest of
641 # attributes you can use direct writer methods. This is meant to protect
642 # sensitive attributes from being overwritten by malicious users
643 # tampering with URLs or forms. If you'd rather start from an all-open
644 # default and restrict attributes as needed, have a look at
645 # +attr_protected+.
d761ac4 Add docs explaining how to protect all attributes using attr_accessib…
Marcel Molina authored Oct 26, 2007
646 #
647 # class Customer < ActiveRecord::Base
f770b82 Enhance explanation with more examples for attr_accessible macro. Clo…
Marcel Molina authored Nov 6, 2007
648 # attr_accessible :name, :nickname
d761ac4 Add docs explaining how to protect all attributes using attr_accessib…
Marcel Molina authored Oct 26, 2007
649 # end
650 #
f770b82 Enhance explanation with more examples for attr_accessible macro. Clo…
Marcel Molina authored Nov 6, 2007
651 # customer = Customer.new(:name => "David", :nickname => "Dave", :credit_rating => "Excellent")
652 # customer.credit_rating # => nil
653 # customer.attributes = { :name => "Jolly fellow", :credit_rating => "Superb" }
654 # customer.credit_rating # => nil
d761ac4 Add docs explaining how to protect all attributes using attr_accessib…
Marcel Molina authored Oct 26, 2007
655 #
f770b82 Enhance explanation with more examples for attr_accessible macro. Clo…
Marcel Molina authored Nov 6, 2007
656 # customer.credit_rating = "Average"
657 # customer.credit_rating # => "Average"
e033b5d @lifo Merge docrails
lifo authored Jul 25, 2009
658 #
659 # If the access logic of your application is richer you can use <tt>Hash#except</tt>
660 # or <tt>Hash#slice</tt> to sanitize the hash of parameters before they are
661 # passed to Active Record.
31c8353 @miloops Don't use local vars before testing its conditional.
miloops authored Aug 3, 2009
662 #
e033b5d @lifo Merge docrails
lifo authored Jul 25, 2009
663 # For example, it could be the case that the list of accessible attributes
664 # for a given model depends on the role of the user:
665 #
666 # # Assumes plan_id is accessible because it depends on the role.
667 # params[:account] = params[:account].except(:plan_id) unless admin?
668 # @account.update_attributes(params[:account])
669 #
670 # Note that +attr_accessible+ is still applied to the received hash. Thus,
671 # with this technique you can at most _narrow_ the list of accessible
672 # attributes for a particular mass-assignment call.
db045db @dhh Initial
dhh authored Nov 24, 2004
673 def attr_accessible(*attributes)
288e947 @clemens Some performance goodness for inheritable attributes.
clemens authored Sep 2, 2008
674 write_inheritable_attribute(:attr_accessible, Set.new(attributes.map(&:to_s)) + (accessible_attributes || []))
db045db @dhh Initial
dhh authored Nov 24, 2004
675 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
676
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored Feb 7, 2005
677 # Returns an array of all the attributes that have been made accessible to mass-assignment.
db045db @dhh Initial
dhh authored Nov 24, 2004
678 def accessible_attributes # :nodoc:
288e947 @clemens Some performance goodness for inheritable attributes.
clemens authored Sep 2, 2008
679 read_inheritable_attribute(:attr_accessible)
db045db @dhh Initial
dhh authored Nov 24, 2004
680 end
681
66d05f5 @technoweenie Add attr_readonly to specify columns that are skipped during a normal…
technoweenie authored Sep 30, 2007
682 # Attributes listed as readonly can be set for a new record, but will be ignored in database updates afterwards.
683 def attr_readonly(*attributes)
288e947 @clemens Some performance goodness for inheritable attributes.
clemens authored Sep 2, 2008
684 write_inheritable_attribute(:attr_readonly, Set.new(attributes.map(&:to_s)) + (readonly_attributes || []))
66d05f5 @technoweenie Add attr_readonly to specify columns that are skipped during a normal…
technoweenie authored Sep 30, 2007
685 end
686
687 # Returns an array of all the attributes that have been specified as readonly.
688 def readonly_attributes
5b61168 @miloops Added arel_attributes_values methods, refactored locking and AR#updat…
miloops authored Apr 30, 2009
689 read_inheritable_attribute(:attr_readonly) || []
66d05f5 @technoweenie Add attr_readonly to specify columns that are skipped during a normal…
technoweenie authored Sep 30, 2007
690 end
c450a36 @dhh Doc fixes
dhh authored Mar 5, 2006
691
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored Dec 10, 2007
692 # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object,
693 # then specify the name of that attribute using this method and it will be handled automatically.
694 # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
695 # class on retrieval or SerializationTypeMismatch will be raised.
1a0cdf7 @dhh Docfix (closes #8096)
dhh authored Jun 23, 2007
696 #
a293278 @lifo Merge docrails
lifo authored Oct 5, 2008
697 # ==== Parameters
1a0cdf7 @dhh Docfix (closes #8096)
dhh authored Jun 23, 2007
698 #
dc4eec1 @lifo Merge docrails:
lifo authored May 9, 2008
699 # * +attr_name+ - The field name that should be serialized.
700 # * +class_name+ - Optional, class name that the object type should be equal to.
1a0cdf7 @dhh Docfix (closes #8096)
dhh authored Jun 23, 2007
701 #
702 # ==== Example
703 # # Serialize a preferences attribute
704 # class User
705 # serialize :preferences
706 # end
db045db @dhh Initial
dhh authored Nov 24, 2004
707 def serialize(attr_name, class_name = Object)
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
708 serialized_attributes[attr_name.to_s] = class_name
db045db @dhh Initial
dhh authored Nov 24, 2004
709 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
710
db045db @dhh Initial
dhh authored Nov 24, 2004
711 # Returns a hash of all the attributes that have been specified for serialization as keys and their class restriction as values.
712 def serialized_attributes
288e947 @clemens Some performance goodness for inheritable attributes.
clemens authored Sep 2, 2008
713 read_inheritable_attribute(:attr_serialized) or write_inheritable_attribute(:attr_serialized, {})
db045db @dhh Initial
dhh authored Nov 24, 2004
714 end
715
716 # Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
717 # directly from ActiveRecord::Base. So if the hierarchy looks like: Reply < Message < ActiveRecord::Base, then Message is used
d64832c Give examples for what tables should be called for models inside a mo…
Marcel Molina authored Dec 5, 2007
718 # to guess the table name even when called on Reply. The rules used to do the guess are handled by the Inflector class
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobS…
Marcel Molina authored Nov 8, 2007
719 # in Active Support, which knows almost all common English inflections. You can add new inflections in config/initializers/inflections.rb.
db045db @dhh Initial
dhh authored Nov 24, 2004
720 #
14101c7 @jeremy Nested classes are given table names prefixed by the singular form of…
jeremy authored Aug 16, 2006
721 # Nested classes are given table names prefixed by the singular form of
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
722 # the parent's table name. Enclosing modules are not considered.
723 #
724 # ==== Examples
d64832c Give examples for what tables should be called for models inside a mo…
Marcel Molina authored Dec 5, 2007
725 #
726 # class Invoice < ActiveRecord::Base; end;
14101c7 @jeremy Nested classes are given table names prefixed by the singular form of…
jeremy authored Aug 16, 2006
727 # file class table_name
728 # invoice.rb Invoice invoices
d64832c Give examples for what tables should be called for models inside a mo…
Marcel Molina authored Dec 5, 2007
729 #
730 # class Invoice < ActiveRecord::Base; class Lineitem < ActiveRecord::Base; end; end;
731 # file class table_name
732 # invoice.rb Invoice::Lineitem invoice_lineitems
733 #
734 # module Invoice; class Lineitem < ActiveRecord::Base; end; end;
735 # file class table_name
736 # invoice/lineitem.rb Invoice::Lineitem lineitems
db045db @dhh Initial
dhh authored Nov 24, 2004
737 #
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
738 # Additionally, the class-level +table_name_prefix+ is prepended and the
739 # +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 Aug 16, 2006
740 # the table name guess for an Invoice class becomes "myapp_invoices".
741 # Invoice::Lineitem becomes "myapp_invoice_lineitems".
742 #
743 # You can also overwrite this class method to allow for unguessable
744 # links, such as a Mouse class with a link to a "mice" table. Example:
db045db @dhh Initial
dhh authored Nov 24, 2004
745 #
746 # class Mouse < ActiveRecord::Base
14101c7 @jeremy Nested classes are given table names prefixed by the singular form of…
jeremy authored Aug 16, 2006
747 # set_table_name "mice"
db045db @dhh Initial
dhh authored Nov 24, 2004
748 # end
dcc4868 @dhh Fixed that Base.table_name would expect a parameter when used in has_…
dhh authored Dec 22, 2004
749 def table_name
d736568 Speed up the setting of table_name. Closes #2428.
Marcel Molina authored Oct 10, 2005
750 reset_table_name
751 end
752
798d282 @lifo Cache quoted_table_name
lifo authored Jan 21, 2010
753 def quoted_table_name
754 @quoted_table_name ||= connection.quote_table_name(table_name)
755 end
756
fed7d33 @dhh Fixed documentation
dhh authored Mar 28, 2006
757 def reset_table_name #:nodoc:
bcbce90 @jeremy Nested subclasses are not prefixed with the parent class' table_name …
jeremy authored Aug 25, 2006
758 base = base_class
759
760 name =
761 # STI subclasses always use their superclass' table.
762 unless self == base
763 base.table_name
764 else
765 # Nested classes are prefixed with singular parent table name.
766 if parent < ActiveRecord::Base && !parent.abstract_class?
767 contained = parent.table_name
768 contained = contained.singularize if parent.pluralize_table_names
769 contained << '_'
770 end
5f7bc47 @wycats Rename modularized_table_name_prefix to full_table_name_prefix [#4032
wycats authored Mar 28, 2010
771 name = "#{full_table_name_prefix}#{contained}#{undecorated_table_name(base.name)}#{table_name_suffix}"
bcbce90 @jeremy Nested subclasses are not prefixed with the parent class' table_name …
jeremy authored Aug 25, 2006
772 end
773
798d282 @lifo Cache quoted_table_name
lifo authored Jan 20, 2010
774 @quoted_table_name = nil
c450a36 @dhh Doc fixes
dhh authored Mar 5, 2006
775 set_table_name(name)
d736568 Speed up the setting of table_name. Closes #2428.
Marcel Molina authored Oct 10, 2005
776 name
db045db @dhh Initial
dhh authored Nov 24, 2004
777 end
778
5f7bc47 @wycats Rename modularized_table_name_prefix to full_table_name_prefix [#4032
wycats authored Mar 29, 2010
779 def full_table_name_prefix #:nodoc:
67d1cec @pixeltrix Add the ability to specify table_name_prefix on individual modules
pixeltrix authored Feb 22, 2010
780 (parents.detect{ |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix
781 end
782
9d2da04 @jeremy Cache inheritance_column. Closes #6592.
jeremy authored Nov 9, 2006
783 # Defines the column name for use with single table inheritance
784 # -- can be set in subclasses like so: self.inheritance_column = "type_id"
db045db @dhh Initial
dhh authored Nov 24, 2004
785 def inheritance_column
9d2da04 @jeremy Cache inheritance_column. Closes #6592.
jeremy authored Nov 9, 2006
786 @inheritance_column ||= "type".freeze
db045db @dhh Initial
dhh authored Nov 24, 2004
787 end
788
7c8f3ed @jeremy r4325@asus: jeremy | 2005-11-12 03:57:46 -0800
jeremy authored Nov 12, 2005
789 # Lazy-set the sequence name to the connection's default. This method
790 # is only ever called once since set_sequence_name overrides it.
fed7d33 @dhh Fixed documentation
dhh authored Mar 28, 2006
791 def sequence_name #:nodoc:
7c8f3ed @jeremy r4325@asus: jeremy | 2005-11-12 03:57:46 -0800
jeremy authored Nov 12, 2005
792 reset_sequence_name
793 end
794
fed7d33 @dhh Fixed documentation
dhh authored Mar 28, 2006
795 def reset_sequence_name #:nodoc:
7c8f3ed @jeremy r4325@asus: jeremy | 2005-11-12 03:57:46 -0800
jeremy authored Nov 12, 2005
796 default = connection.default_sequence_name(table_name, primary_key)
797 set_sequence_name(default)
798 default
14ea312 @dhh Made Oracle a first-class connection adapter by adhering closer to id…
dhh authored Jul 24, 2005
799 end
800
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindings
dhh authored Feb 7, 2005
801 # Sets the table name to use to the given value, or (if the value
4eab375 @dhh Finished polishing API docs
dhh authored Feb 23, 2005
802 # is nil or false) to the value returned by the given block.
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindings
dhh authored Feb 7, 2005
803 #
804 # class Project < ActiveRecord::Base
805 # set_table_name "project"
806 # end
c9c1852 @dhh Making ActiveRecord faster [skaes]
dhh authored Mar 27, 2006
807 def set_table_name(value = nil, &block)
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindings
dhh authored Feb 7, 2005
808 define_attr_method :table_name, value, &block
809 end
810 alias :table_name= :set_table_name
811
812 # Sets the name of the inheritance column to use to the given value,
813 # or (if the value # is nil or false) to the value returned by the
4eab375 @dhh Finished polishing API docs
dhh authored Feb 23, 2005
814 # given block.
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindings
dhh authored Feb 7, 2005
815 #
816 # class Project < ActiveRecord::Base
817 # set_inheritance_column do
818 # original_inheritance_column + "_id"
819 # end
820 # end
c9c1852 @dhh Making ActiveRecord faster [skaes]
dhh authored Mar 27, 2006
821 def set_inheritance_column(value = nil, &block)
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindings
dhh authored Feb 7, 2005
822 define_attr_method :inheritance_column, value, &block
823 end
824 alias :inheritance_column= :set_inheritance_column
825
14ea312 @dhh Made Oracle a first-class connection adapter by adhering closer to id…
dhh authored Jul 24, 2005
826 # Sets the name of the sequence to use when generating ids to the given
827 # 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 Oct 16, 2005
828 # given block. This is required for Oracle and is useful for any
829 # 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 Jul 24, 2005
830 #
2076dca @jeremy r3095@asus: jeremy | 2005-11-15 22:40:51 -0800
jeremy authored Nov 16, 2005
831 # If a sequence name is not explicitly set when using Oracle or Firebird,
832 # it will default to the commonly used pattern of: #{table_name}_seq
833 #
834 # If a sequence name is not explicitly set when using PostgreSQL, it
835 # 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 Jul 24, 2005
836 #
837 # class Project < ActiveRecord::Base
838 # set_sequence_name "projectseq" # default would have been "project_seq"
839 # end
c9c1852 @dhh Making ActiveRecord faster [skaes]
dhh authored Mar 27, 2006
840 def set_sequence_name(value = nil, &block)
14ea312 @dhh Made Oracle a first-class connection adapter by adhering closer to id…
dhh authored Jul 24, 2005
841 define_attr_method :sequence_name, value, &block
842 end
843 alias :sequence_name= :set_sequence_name
844
db045db @dhh Initial
dhh authored Nov 24, 2004
845 # Turns the +table_name+ back into a class name following the reverse rules of +table_name+.
846 def class_name(table_name = table_name) # :nodoc:
847 # remove any prefix and/or suffix from the table name
81737fc @jeremy r1613@asus: jeremy | 2005-07-03 07:04:53 -0700
jeremy authored Jul 3, 2005
848 class_name = table_name[table_name_prefix.length..-(table_name_suffix.length + 1)].camelize
849 class_name = class_name.singularize if pluralize_table_names
850 class_name
db045db @dhh Initial
dhh authored Nov 24, 2004
851 end
852
816f37a @dhh Added migration support to SQL Server adapter (please someone do the …
dhh authored Oct 28, 2005
853 # Indicates whether the table associated with this class exists
854 def table_exists?
8877ab5 @tarmo Added AbstractAdapter#table_exists? and made AbstractAdapter#table im…
tarmo authored May 7, 2008
855 connection.table_exists?(table_name)
816f37a @dhh Added migration support to SQL Server adapter (please someone do the …
dhh authored Oct 28, 2005
856 end
857
db045db @dhh Initial
dhh authored Nov 24, 2004
858 # Returns an array of column objects for the table associated with this class.
859 def columns
8b5f4e4 @jeremy Ruby 1.9 compat: fix warnings, shadowed block vars, and unitialized i…
jeremy authored Dec 22, 2007
860 unless defined?(@columns) && @columns
c0899bc Add convenience predicate methods on Column class. In partial fullfil…
Marcel Molina authored Oct 6, 2005
861 @columns = connection.columns(table_name, "#{name} Columns")
8b5f4e4 @jeremy Ruby 1.9 compat: fix warnings, shadowed block vars, and unitialized i…
jeremy authored Dec 22, 2007
862 @columns.each { |column| column.primary = column.name == primary_key }
c0899bc Add convenience predicate methods on Column class. In partial fullfil…
Marcel Molina authored Oct 6, 2005
863 end
864 @columns
db045db @dhh Initial
dhh authored Nov 24, 2004
865 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
866
3b4450b @NZKoz Docs fix for columns_hash [bradediger]
NZKoz authored Dec 27, 2006
867 # Returns a hash of column objects for the table associated with this class.
db045db @dhh Initial
dhh authored Nov 24, 2004
868 def columns_hash
869 @columns_hash ||= columns.inject({}) { |hash, column| hash[column.name] = column; hash }
870 end
d0bd3b5 @jeremy Return PostgreSQL columns in the order they are declared #1374 (perlg…
jeremy authored Jun 12, 2005
871
fed7d33 @dhh Fixed documentation
dhh authored Mar 28, 2006
872 # Returns an array of column names as strings.
49d0f0c @dhh Speeded up eager loading a whole bunch
dhh authored Apr 18, 2005
873 def column_names
d0bd3b5 @jeremy Return PostgreSQL columns in the order they are declared #1374 (perlg…
jeremy authored Jun 12, 2005
874 @column_names ||= columns.map { |column| column.name }
49d0f0c @dhh Speeded up eager loading a whole bunch
dhh authored Apr 18, 2005
875 end
db045db @dhh Initial
dhh authored Nov 24, 2004
876
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored Oct 11, 2005
877 # Returns an array of column objects where the primary id, all columns ending in "_id" or "_count",
878 # and columns used for single table inheritance have been removed.
db045db @dhh Initial
dhh authored Nov 24, 2004
879 def content_columns
c0899bc Add convenience predicate methods on Column class. In partial fullfil…
Marcel Molina authored Oct 6, 2005
880 @content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column }
db045db @dhh Initial
dhh authored Nov 24, 2004
881 end
882
883 # 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
884 # 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 Jul 3, 2005
885 # is available.
fed7d33 @dhh Fixed documentation
dhh authored Mar 28, 2006
886 def column_methods_hash #:nodoc:
d0bd3b5 @jeremy Return PostgreSQL columns in the order they are declared #1374 (perlg…
jeremy authored Jun 12, 2005
887 @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 Oct 22, 2005
888 attr_name = attr.to_s
889 methods[attr.to_sym] = attr_name
890 methods["#{attr}=".to_sym] = attr_name
891 methods["#{attr}?".to_sym] = attr_name
892 methods["#{attr}_before_type_cast".to_sym] = attr_name
db045db @dhh Initial
dhh authored Nov 24, 2004
893 methods
894 end
895 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
896
a293278 @lifo Merge docrails
lifo authored Oct 5, 2008
897 # Resets all the cached information about columns, which will cause them
898 # to be reloaded on the next request.
899 #
900 # The most common usage pattern for this method is probably in a migration,
901 # when just after creating a table you want to populate it with some default
902 # values, eg:
903 #
904 # class CreateJobLevels < ActiveRecord::Migration
905 # def self.up
906 # create_table :job_levels do |t|
907 # t.integer :id
908 # t.string :name
909 #
910 # t.timestamps
911 # end
912 #
913 # JobLevel.reset_column_information
914 # %w{assistant executive manager director}.each do |type|
915 # JobLevel.create(:name => type)
916 # end
917 # end
918 #
919 # def self.down
920 # drop_table :job_levels
921 # end
922 # end
1314f48 @dhh Added methods for resetting the cached information on classes that yo…
dhh authored Dec 12, 2004
923 def reset_column_information
e129c56 @josh Wrap up attribute method reset concerns in 'undefine_attribute_methods'
josh authored Jul 29, 2009
924 undefine_attribute_methods
d2c4b3b @lifo Rename Model.engine to active_relation_engine. Cache arel_table and t…
lifo authored Jan 2, 2010
925 @column_names = @columns = @columns_hash = @content_columns = @dynamic_methods_hash = @inheritance_column = nil
6e3bee6 @lifo Cache Model.arel_table
lifo authored Jan 17, 2010
926 @arel_engine = @unscoped = @arel_table = nil
1314f48 @dhh Added methods for resetting the cached information on classes that yo…
dhh authored Dec 12, 2004
927 end
928
4eab375 @dhh Finished polishing API docs
dhh authored Feb 23, 2005
929 def reset_column_information_and_inheritable_attributes_for_all_subclasses#:nodoc:
1314f48 @dhh Added methods for resetting the cached information on classes that yo…
dhh authored Dec 12, 2004
930 subclasses.each { |klass| klass.reset_inheritable_attributes; klass.reset_column_information }
931 end
db045db @dhh Initial
dhh authored Nov 24, 2004
932
e714b49 @josevalim Move validator, human_name and human_attribute_name to ActiveModel, r…
josevalim authored Oct 20, 2009
933 # Set the lookup ancestors for ActiveModel.
934 def lookup_ancestors #:nodoc:
ffeab4e Cleaned up ActiveRecord i18n scoping
Iain Hecker authored Aug 14, 2008
935 klass = self
936 classes = [klass]
0905396 @miloops construct_finder_sql now use Arel
miloops authored Apr 25, 2009
937 while klass != klass.base_class
ffeab4e Cleaned up ActiveRecord i18n scoping
Iain Hecker authored Aug 13, 2008
938 classes << klass = klass.superclass
939 end
940 classes
941 rescue
942 # OPTIMIZE this rescue is to fix this test: ./test/cases/reflection_test.rb:56:in `test_human_name_for_column'
e033b5d @lifo Merge docrails
lifo authored Jul 25, 2009
943 # Apparently the method base_class causes some trouble.
ffeab4e Cleaned up ActiveRecord i18n scoping
Iain Hecker authored Aug 13, 2008
944 # It now works for sure.
945 [self]
946 end
947
e714b49 @josevalim Move validator, human_name and human_attribute_name to ActiveModel, r…
josevalim authored Oct 21, 2009
948 # Set the i18n scope to overwrite ActiveModel.
949 def i18n_scope #:nodoc:
950 :activerecord
db045db @dhh Initial
dhh authored Nov 24, 2004
951 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored Jul 3, 2005
952
06afb8c @jeremy Subclasses of an abstract class work with single-table inheritance. R…
jeremy authored Jan 23, 2007
953 # True if this isn't a concrete subclass needing a STI type condition.
954 def descends_from_active_record?
955 if superclass.abstract_class?
956 superclass.descends_from_active_record?
957 else
958 superclass == Base || !columns_hash.include?(inheritance_column)
959 end
db045db @dhh Initial
dhh authored Nov 24, 2004
960 end
961
b4ec990 @NZKoz Cache the descends_from_activerecord? call to speed up query generati…
NZKoz authored Oct 3, 2007
962 def finder_needs_type_condition? #:nodoc:
963 # This is like this because benchmarking justifies the strange :false stuff
964 :true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true)
965 end
966
d0360a4 @jeremy Base.inspect handles Base itself and abstract_class? Don't use #<Foo …
jeremy authored May 31, 2007
967 # 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 Apr 21, 2007
968 def inspect
d0360a4 @jeremy Base.inspect handles Base itself and abstract_class? Don't use #<Foo …
jeremy authored May 31, 2007
969 if self == Base
970 super
971 elsif abstract_class?
972 "#{super}(abstract)"
bb94ce9 @NZKoz Let inspect on AR classes work when the table doesn't exist. Closes #…
NZKoz authored Aug 6, 2007
973 elsif table_exists?
d0360a4 @jeremy Base.inspect handles Base itself and abstract_class? Don't use #<Foo …
jeremy authored May 31, 2007
974 attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', '
975 "#{super}(#{attr_list})"
bb94ce9 @NZKoz Let inspect on AR classes work when the table doesn't exist. Closes #…
NZKoz authored Aug 6, 2007
976 else
977 "#{super}(Table doesn't exist)"
d0360a4 @jeremy Base.inspect handles Base itself and abstract_class? Don't use #<Foo …
jeremy authored May 31, 2007
978 end
52a9e50 @dhh Added ActiveRecord::Base.inspect to return a column-view like #<Post …
dhh authored Apr 21, 2007
979 end
980
b445ab9 @NZKoz Rename quote to quote_value so the name can be used in AR models. #3628
NZKoz authored Sep 4, 2006
981 def quote_value(value, column = nil) #:nodoc:
b2c0ddf Add support for FrontBase (http://www.frontbase.com/) with a new adap…
Marcel Molina authored Apr 27, 2006
982 connection.quote(value,column)
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored Dec 7, 2004
983 end
984
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobS…
Marcel Molina authored Nov 8, 2007
985 # 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 Feb 23, 2005
986 def sanitize(object) #:nodoc:
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored Dec 7, 2004
987 connection.quote(object)
db045db @dhh Initial
dhh authored Nov 24, 2004
988 end
989
97849de @dhh Fixed that association proxies would fail === tests like PremiumSubsc…
dhh authored Jan 23, 2005
990 # Overwrite the default class equality method to provide support for association proxies.
991 def ===(object)
992 object.is_a?(self)
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored Dec 10, 2007
993 end
b840e4e Deprecated ActiveRecord::Base.threaded_connection in favor of ActiveR…
Marcel Molina authored Oct 12, 2005
994
d2f4750 @jamis Add AR::Base.base_class for querying the ancestor AR::Base subclass […
jamis authored Jan 20, 2006
995 # Returns the base AR subclass that this class descends from. If A
996 # extends AR::Base, A.base_class will return A. If B descends from A
997 # through some arbitrarily deep hierarchy, B.base_class will return A.
998 def base_class
999 class_of_active_record_descendant(self)
1000 end
1001
98dc582 @lifo Merge docrails.
lifo authored May 25, 2008
1002 # 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 Mar 16, 2006
1003 attr_accessor :abstract_class
1004
1005 # Returns whether this class is a base AR class. If A is a base class and
1006 # B descends from A, then B.base_class will return B.
1007 def abstract_class?
8b5f4e4 @jeremy Ruby 1.9 compat: fix warnings, shadowed block vars, and unitialized i…
jeremy authored Dec 22, 2007
1008 defined?(@abstract_class) && @abstract_class == true
def7460 @technoweenie Added Base.abstract_class? that marks which classes are not part of t…
technoweenie authored Mar 16, 2006
1009 end
1010
4f39382 @lifo Ensure that respond_to? considers dynamic finder methods. Closes #11538
lifo authored Apr 6, 2008
1011 def respond_to?(method_id, include_private = false)
143f5fb @joshsusser refactor dynamic finder name matching into its own class
joshsusser authored Aug 25, 2008
1012