Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

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