Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100755 3165 lines (2859 sloc) 139.565 kB
db045db @dhh Initial
dhh authored
1 require 'yaml'
aabf909 @jeremy Correct reader method generation for primary key attribute: handle ca…
jeremy authored
2 require 'set'
f5d720f @jeremy Opt in to Dependencies
jeremy authored
3 require 'active_support/dependencies'
5f222c5 @jeremy Remove 'core' fluff. Hookable ActiveSupport.load_all!
jeremy authored
4 require 'active_support/time'
e8550ee @jeremy Cherry-pick core extensions
jeremy authored
5 require 'active_support/core_ext/class/attribute_accessors'
6 require 'active_support/core_ext/class/delegating_attributes'
7 require 'active_support/core_ext/class/inheritable_attributes'
8 require 'active_support/core_ext/array/extract_options'
9 require 'active_support/core_ext/hash/deep_merge'
10 require 'active_support/core_ext/hash/indifferent_access'
11 require 'active_support/core_ext/hash/slice'
12 require 'active_support/core_ext/string/behavior'
a69b28a @jeremy Missing 1.8.7 backport extensions
jeremy authored
13 require 'active_support/core_ext/symbol'
db045db @dhh Initial
dhh authored
14
15 module ActiveRecord #:nodoc:
98dc582 @lifo Merge docrails.
lifo authored
16 # Generic Active Record exception class.
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
17 class ActiveRecordError < StandardError
db045db @dhh Initial
dhh authored
18 end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
19
0432d15 @lifo Merge with docrails.
lifo authored
20 # Raised when the single-table inheritance mechanism fails to locate the subclass
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
21 # (for example due to improper usage of column that +inheritance_column+ points to).
605bc77 @dhh Added a better exception for when a type column is used in a table wi…
dhh authored
22 class SubclassNotFound < ActiveRecordError #:nodoc:
23 end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
24
64092de @fxn Improve documentation coverage and markup
fxn authored
25 # Raised when an object assigned to an association has an incorrect type.
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
26 #
64092de @fxn Improve documentation coverage and markup
fxn authored
27 # class Ticket < ActiveRecord::Base
28 # has_many :patches
29 # end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
30 #
64092de @fxn Improve documentation coverage and markup
fxn authored
31 # class Patch < ActiveRecord::Base
32 # belongs_to :ticket
33 # end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
34 #
64092de @fxn Improve documentation coverage and markup
fxn authored
35 # # Comments are not patches, this assignment raises AssociationTypeMismatch.
36 # @ticket.patches << Comment.new(:content => "Please attach tests to your patch.")
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
37 class AssociationTypeMismatch < ActiveRecordError
db045db @dhh Initial
dhh authored
38 end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
39
40 # Raised when unserialized object's type mismatches one specified for serializable field.
41 class SerializationTypeMismatch < ActiveRecordError
db045db @dhh Initial
dhh authored
42 end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
43
98dc582 @lifo Merge docrails.
lifo authored
44 # Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt> misses adapter field).
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
45 class AdapterNotSpecified < ActiveRecordError
db045db @dhh Initial
dhh authored
46 end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
47
98dc582 @lifo Merge docrails.
lifo authored
48 # Raised when Active Record cannot find database adapter specified in <tt>config/database.yml</tt> or programmatically.
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
49 class AdapterNotFound < ActiveRecordError
db045db @dhh Initial
dhh authored
50 end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
51
98dc582 @lifo Merge docrails.
lifo authored
52 # Raised when connection to the database could not been established (for example when <tt>connection=</tt> is given a nil object).
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
53 class ConnectionNotEstablished < ActiveRecordError
db045db @dhh Initial
dhh authored
54 end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
55
98dc582 @lifo Merge docrails.
lifo authored
56 # Raised when Active Record cannot find record by given id or set of ids.
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
57 class RecordNotFound < ActiveRecordError
db045db @dhh Initial
dhh authored
58 end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
59
60 # Raised by ActiveRecord::Base.save! and ActiveRecord::Base.create! methods when record cannot be
61 # saved because record is invalid.
62 class RecordNotSaved < ActiveRecordError
4c7555a @dhh Fixed that Base.save should always return false if the save didn't su…
dhh authored
63 end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
64
65 # Raised when SQL statement cannot be executed by the database (for example, it's often the case for MySQL when Ruby driver used is too old).
66 class StatementInvalid < ActiveRecordError
db045db @dhh Initial
dhh authored
67 end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
68
64092de @fxn Improve documentation coverage and markup
fxn authored
69 # Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example, when using +find+ method)
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
70 # does not match number of expected variables.
71 #
64092de @fxn Improve documentation coverage and markup
fxn authored
72 # For example, in
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
73 #
64092de @fxn Improve documentation coverage and markup
fxn authored
74 # Location.find :all, :conditions => ["lat = ? AND lng = ?", 53.7362]
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
75 #
64092de @fxn Improve documentation coverage and markup
fxn authored
76 # two placeholders are given but only one variable to fill them.
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
77 class PreparedStatementInvalid < ActiveRecordError
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
78 end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
79
80 # Raised on attempt to save stale record. Record is stale when it's being saved in another query after
81 # instantiation, for example, when two users edit the same wiki page and one starts editing and saves
82 # the page before the other.
83 #
98dc582 @lifo Merge docrails.
lifo authored
84 # Read more about optimistic locking in ActiveRecord::Locking module RDoc.
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
85 class StaleObjectError < ActiveRecordError
fbf9281 @dhh Added automated optimistic locking if the field lock_version is prese…
dhh authored
86 end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
87
88 # Raised when association is being configured improperly or
89 # user tries to use offset and limit together with has_many or has_and_belongs_to_many associations.
90 class ConfigurationError < ActiveRecordError
5b9b904 @dhh Added support for limit and offset with eager loading of has_one and …
dhh authored
91 end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
92
93 # Raised on attempt to update record that is instantiated as read only.
94 class ReadOnlyRecord < ActiveRecordError
64fcb75 @jeremy r3618@sedna: jeremy | 2005-10-14 12:06:03 -0700
jeremy authored
95 end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
96
6e75455 @lifo Merge docrails changes
lifo authored
97 # ActiveRecord::Transactions::ClassMethods.transaction uses this exception
98 # to distinguish a deliberate rollback from other exceptional situations.
99 # Normally, raising an exception will cause the +transaction+ method to rollback
100 # the database transaction *and* pass on the exception. But if you raise an
101 # ActiveRecord::Rollback exception, then the database transaction will be rolled back,
102 # without passing on the exception.
103 #
104 # For example, you could do this in your controller to rollback a transaction:
105 #
106 # class BooksController < ActionController::Base
107 # def create
108 # Book.transaction do
109 # book = Book.new(params[:book])
110 # book.save!
111 # if today_is_friday?
112 # # The system must fail on Friday so that our support department
113 # # won't be out of job. We silently rollback this transaction
114 # # without telling the user.
115 # raise ActiveRecord::Rollback, "Call tech support!"
116 # end
117 # end
118 # # ActiveRecord::Rollback is the only exception that won't be passed on
119 # # by ActiveRecord::Base.transaction, so this line will still be reached
120 # # even on Friday.
121 # redirect_to root_url
122 # end
123 # end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
124 class Rollback < ActiveRecordError
5b2e8b1 @technoweenie Fix that ActiveRecord would create attribute methods and override cus…
technoweenie authored
125 end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
126
98dc582 @lifo Merge docrails.
lifo authored
127 # Raised when attribute has a name reserved by Active Record (when attribute has name of one of Active Record instance methods).
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
128 class DangerousAttributeError < ActiveRecordError
ebbe4fb @NZKoz Replace the transaction {|transaction|..} semantics with a new Except…
NZKoz authored
129 end
84a14f2 @jeremy Raise ProtectedAttributeAssignmentError in development and test envir…
jeremy authored
130
dc4eec1 @lifo Merge docrails:
lifo authored
131 # Raised when you've tried to access a column which wasn't loaded by your finder.
132 # Typically this is because <tt>:select</tt> has been specified.
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writ…
NZKoz authored
133 class MissingAttributeError < NoMethodError
134 end
e48b062 @jeremy Sanitize Base#inspect. Closes #8392.
jeremy authored
135
4f68752 @jeremy Revert "Revert "Raise UnknownAttributeError when unknown attributes a…
jeremy authored
136 # Raised when unknown attributes are supplied via mass assignment.
137 class UnknownAttributeError < NoMethodError
138 end
139
0432d15 @lifo Merge with docrails.
lifo authored
140 # Raised when an error occurred while doing a mass assignment to an attribute through the
dc4eec1 @lifo Merge docrails:
lifo authored
141 # <tt>attributes=</tt> method. The exception has an +attribute+ property that is the name of the
142 # offending attribute.
143 class AttributeAssignmentError < ActiveRecordError
d2fefbe @dhh Added MultiparameterAssignmentErrors and AttributeAssignmentError exc…
dhh authored
144 attr_reader :exception, :attribute
145 def initialize(message, exception, attribute)
146 @exception = exception
147 @attribute = attribute
148 @message = message
149 end
150 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
151
dc4eec1 @lifo Merge docrails:
lifo authored
152 # Raised when there are multiple errors while doing a mass assignment through the +attributes+
153 # method. The exception has an +errors+ property that contains an array of AttributeAssignmentError
154 # objects, each corresponding to the error while assigning to an attribute.
155 class MultiparameterAssignmentErrors < ActiveRecordError
d2fefbe @dhh Added MultiparameterAssignmentErrors and AttributeAssignmentError exc…
dhh authored
156 attr_reader :errors
157 def initialize(errors)
158 @errors = errors
159 end
160 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
161
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
162 # Active Record objects don't specify their attributes directly, but rather infer them from the table definition with
db045db @dhh Initial
dhh authored
163 # which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change
164 # 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
165 # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
166 #
db045db @dhh Initial
dhh authored
167 # 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
168 #
db045db @dhh Initial
dhh authored
169 # == Creation
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
170 #
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
171 # Active Records accept constructor parameters either in a hash or as a block. The hash method is especially useful when
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobS…
Marcel Molina authored
172 # 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
173 #
0591c53 @dhh Made the dynamic finders use the new find API and updated the example…
dhh authored
174 # user = User.new(:name => "David", :occupation => "Code Artist")
db045db @dhh Initial
dhh authored
175 # user.name # => "David"
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
176 #
db045db @dhh Initial
dhh authored
177 # You can also use block initialization:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
178 #
db045db @dhh Initial
dhh authored
179 # user = User.new do |u|
180 # u.name = "David"
181 # u.occupation = "Code Artist"
182 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
183 #
db045db @dhh Initial
dhh authored
184 # 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
185 #
db045db @dhh Initial
dhh authored
186 # user = User.new
187 # user.name = "David"
188 # user.occupation = "Code Artist"
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
189 #
db045db @dhh Initial
dhh authored
190 # == Conditions
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
191 #
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored
192 # Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement.
db045db @dhh Initial
dhh authored
193 # The array form is to be used when the condition input is tainted and requires sanitization. The string form can
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored
194 # be used for statements that don't involve tainted data. The hash form works much like the array form, except
2876707 @jeremy Pass a range in :conditions to use the SQL BETWEEN operator. Closes #…
jeremy authored
195 # only equality and range is possible. Examples:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
196 #
48052d7 @jeremy to_xml fixes, features, and speedup. Closes #4989.
jeremy authored
197 # class User < ActiveRecord::Base
db045db @dhh Initial
dhh authored
198 # def self.authenticate_unsafely(user_name, password)
3dfa56c @dhh Updated all references to the old find_first and find_all to use the …
dhh authored
199 # find(:first, :conditions => "user_name = '#{user_name}' AND password = '#{password}'")
db045db @dhh Initial
dhh authored
200 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
201 #
db045db @dhh Initial
dhh authored
202 # def self.authenticate_safely(user_name, password)
3dfa56c @dhh Updated all references to the old find_first and find_all to use the …
dhh authored
203 # find(:first, :conditions => [ "user_name = ? AND password = ?", user_name, password ])
db045db @dhh Initial
dhh authored
204 # end
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored
205 #
206 # def self.authenticate_safely_simply(user_name, password)
207 # find(:first, :conditions => { :user_name => user_name, :password => password })
208 # end
db045db @dhh Initial
dhh authored
209 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
210 #
2575b3b @dhh Added extra words of caution for guarding against SQL-injection attacks
dhh authored
211 # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobS…
Marcel Molina authored
212 # 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
213 # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+ before inserting them in the query,
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored
214 # 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
215 #
5cd38ca @dhh Added documentation about named bind variables
dhh authored
216 # 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
217 # 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
218 # the question marks with symbols and supplying a hash with values for the matching symbol keys:
219 #
a7e6e00 Documentation for find incorrectly omits the :conditions option from …
Marcel Molina authored
220 # Company.find(:first, :conditions => [
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
221 # "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
5cd38ca @dhh Added documentation about named bind variables
dhh authored
222 # { :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' }
223 # ])
224 #
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored
225 # Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
226 # operator. For instance:
227 #
228 # Student.find(:all, :conditions => { :first_name => "Harvey", :status => 1 })
229 # Student.find(:all, :conditions => params[:student])
230 #
2876707 @jeremy Pass a range in :conditions to use the SQL BETWEEN operator. Closes #…
jeremy authored
231 # A range may be used in the hash to use the SQL BETWEEN operator:
232 #
233 # Student.find(:all, :conditions => { :grade => 9..12 })
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an …
dhh authored
234 #
aa4af60 @lifo Improve documentation.
lifo authored
235 # An array may be used in the hash to use the SQL IN operator:
236 #
237 # Student.find(:all, :conditions => { :grade => [9,11,12] })
238 #
db045db @dhh Initial
dhh authored
239 # == Overwriting default accessors
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
240 #
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobS…
Marcel Molina authored
241 # All column values are automatically available through basic accessors on the Active Record object, but sometimes you
242 # want to specialize this behavior. This can be done by overwriting the default accessors (using the same
98dc582 @lifo Merge docrails.
lifo authored
243 # 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
244 # Example:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
245 #
db045db @dhh Initial
dhh authored
246 # class Song < ActiveRecord::Base
247 # # 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
248 #
db045db @dhh Initial
dhh authored
249 # def length=(minutes)
64092de @fxn Improve documentation coverage and markup
fxn authored
250 # write_attribute(:length, minutes.to_i * 60)
db045db @dhh Initial
dhh authored
251 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
252 #
db045db @dhh Initial
dhh authored
253 # def length
0591c53 @dhh Made the dynamic finders use the new find API and updated the example…
dhh authored
254 # read_attribute(:length) / 60
db045db @dhh Initial
dhh authored
255 # end
256 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
257 #
98dc582 @lifo Merge docrails.
lifo authored
258 # You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt> instead of <tt>write_attribute(:attribute, value)</tt> and
259 # <tt>read_attribute(:attribute)</tt> as a shorter form.
0591c53 @dhh Made the dynamic finders use the new find API and updated the example…
dhh authored
260 #
e4d845e Document automatically generated predicate methods for attributes. Cl…
Marcel Molina authored
261 # == Attribute query methods
262 #
263 # In addition to the basic accessors, query methods are also automatically available on the Active Record object.
264 # Query methods allow you to test whether an attribute value is present.
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
265 #
e4d845e Document automatically generated predicate methods for attributes. Cl…
Marcel Molina authored
266 # For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
267 # to determine whether the user has a name:
268 #
269 # user = User.new(:name => "David")
270 # user.name? # => true
271 #
272 # anonymous = User.new(:name => "")
273 # anonymous.name? # => false
274 #
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
275 # == Accessing attributes before they have been typecasted
4eab375 @dhh Finished polishing API docs
dhh authored
276 #
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
277 # 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
278 # 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
279 # 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
280 #
281 # 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
282 # 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
283 # want.
284 #
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting obj…
dhh authored
285 # == Dynamic attribute-based finders
286 #
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many …
dhh authored
287 # 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
288 # 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
289 # <tt>Person.find_all_by_last_name</tt>, and <tt>Payment.find_by_transaction_id</tt>. So instead of writing
a7e6e00 Documentation for find incorrectly omits the :conditions option from …
Marcel Molina authored
290 # <tt>Person.find(:first, :conditions => ["user_name = ?", user_name])</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
291 # And instead of writing <tt>Person.find(:all, :conditions => ["last_name = ?", last_name])</tt>, you just do <tt>Person.find_all_by_last_name(last_name)</tt>.
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
292 #
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting obj…
dhh authored
293 # It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like
294 # <tt>Person.find_by_user_name_and_password</tt> or even <tt>Payment.find_by_purchaser_and_state_and_country</tt>. So instead of writing
a7e6e00 Documentation for find incorrectly omits the :conditions option from …
Marcel Molina authored
295 # <tt>Person.find(:first, :conditions => ["user_name = ? AND password = ?", user_name, password])</tt>, you just do
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting obj…
dhh authored
296 # <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
297 #
98dc582 @lifo Merge docrails.
lifo authored
298 # It's even possible to use all the additional parameters to find. For example, the full interface for <tt>Payment.find_all_by_amount</tt>
299 # is actually <tt>Payment.find_all_by_amount(amount, options)</tt>. And the full interface to <tt>Person.find_by_user_name</tt> is
64092de @fxn Improve documentation coverage and markup
fxn authored
300 # actually <tt>Person.find_by_user_name(user_name, options)</tt>. So you could call <tt>Payment.find_all_by_amount(50, :order => "created_on")</tt>.
567392b @miloops Added find_last_by dynamic finder [status:committed #762]
miloops authored
301 # Also you may call <tt>Payment.find_last_by_amount(amount, options)</tt> returning the last record matching that amount and options.
959f362 @dhh Added find_all style to the new dynamic finders
dhh authored
302 #
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many …
dhh authored
303 # 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
304 # <tt>find_or_create_by_</tt> and will return the object if it already exists and otherwise creates it, then returns it. Protected attributes won't be set unless they are given in a block. For example:
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many …
dhh authored
305 #
306 # # No 'Summer' tag exists
307 # Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
308 #
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many …
dhh authored
309 # # Now the 'Summer' tag does exist
310 # Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
311 #
c10b225 @dhh Fixed that ActiveRecord#Base.find_or_create/initialize would not hono…
dhh authored
312 # # Now 'Bob' exist and is an 'admin'
313 # User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }
314 #
0432d15 @lifo Merge with docrails.
lifo authored
315 # Use the <tt>find_or_initialize_by_</tt> finder if you want to return a new record without saving it first. Protected attributes won't be set unless they are given in a block. For example:
d19e464 @sstephenson Added find_or_initialize_by_X which works like find_or_create_by_X bu…
sstephenson authored
316 #
317 # # No 'Winter' tag exists
318 # winter = Tag.find_or_initialize_by_name("Winter")
85fbb22 @dhh Backed out of new_record? to new? transformation as it would screw up…
dhh authored
319 # winter.new_record? # true
d19e464 @sstephenson Added find_or_initialize_by_X which works like find_or_create_by_X bu…
sstephenson authored
320 #
14cc8d2 @jeremy find_or_create_by_* takes a hash so you can create with more attribut…
jeremy authored
321 # To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of
322 # a list of parameters. For example:
323 #
324 # Tag.find_or_create_by_name(:name => "rails", :creator => current_user)
325 #
326 # That will either find an existing tag named "rails", or create a new one while setting the user that created it.
327 #
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
328 # == 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
329 #
330 # 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
331 # 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
332 #
db045db @dhh Initial
dhh authored
333 # class User < ActiveRecord::Base
334 # serialize :preferences
335 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
336 #
ca2eb16 Fix syntax error in documentation. Closes #4679. [mislav@nippur.irb.hr]
Marcel Molina authored
337 # user = User.create(:preferences => { "background" => "black", "display" => large })
db045db @dhh Initial
dhh authored
338 # User.find(user.id).preferences # => { "background" => "black", "display" => large }
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
339 #
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
340 # 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
341 # descendant of a class not in the hierarchy. Example:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
342 #
db045db @dhh Initial
dhh authored
343 # class User < ActiveRecord::Base
66f44e6 @dhh Updated documentation for serialize
dhh authored
344 # serialize :preferences, Hash
db045db @dhh Initial
dhh authored
345 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
346 #
0591c53 @dhh Made the dynamic finders use the new find API and updated the example…
dhh authored
347 # user = User.create(:preferences => %w( one two three ))
db045db @dhh Initial
dhh authored
348 # User.find(user.id).preferences # raises SerializationTypeMismatch
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
349 #
db045db @dhh Initial
dhh authored
350 # == Single table inheritance
351 #
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobS…
Marcel Molina authored
352 # 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
353 # by overwriting <tt>Base.inheritance_column</tt>). This means that an inheritance looking like this:
354 #
355 # class Company < ActiveRecord::Base; end
356 # class Firm < Company; end
357 # class Client < Company; end
358 # class PriorityClient < Client; end
359 #
98dc582 @lifo Merge docrails.
lifo authored
360 # When you do <tt>Firm.create(:name => "37signals")</tt>, this record will be saved in the companies table with type = "Firm". You can then
361 # fetch this row again using <tt>Company.find(:first, "name = '37signals'")</tt> and it will return a Firm object.
db045db @dhh Initial
dhh authored
362 #
f033833 @dhh Improving documentation...
dhh authored
363 # 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
364 # like normal subclasses with no special magic for differentiating between them or reloading the right type with find.
365 #
db045db @dhh Initial
dhh authored
366 # Note, all the attributes for all the cases are kept in the same table. Read more:
367 # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
368 #
db045db @dhh Initial
dhh authored
369 # == Connection to multiple databases in different models
370 #
371 # 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
372 # 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
373 # For example, if Course is an ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
374 # and Course and all of its subclasses will use this connection instead.
db045db @dhh Initial
dhh authored
375 #
376 # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is
377 # requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool.
378 #
379 # == Exceptions
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
380 #
dc4eec1 @lifo Merge docrails:
lifo authored
381 # * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record.
382 # * AdapterNotSpecified - The configuration hash used in <tt>establish_connection</tt> didn't include an
db045db @dhh Initial
dhh authored
383 # <tt>:adapter</tt> key.
dc4eec1 @lifo Merge docrails:
lifo authored
384 # * 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
385 # (or a bad spelling of an existing one).
dc4eec1 @lifo Merge docrails:
lifo authored
386 # * AssociationTypeMismatch - The object assigned to the association wasn't of the type specified in the association definition.
387 # * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
388 # * ConnectionNotEstablished+ - No connection has been established. Use <tt>establish_connection</tt> before querying.
389 # * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
390 # or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
391 # nothing was found, please check its documentation for further details.
392 # * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
393 # * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the
394 # <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of AttributeAssignmentError
d2fefbe @dhh Added MultiparameterAssignmentErrors and AttributeAssignmentError exc…
dhh authored
395 # objects that should be inspected to determine which attributes triggered the errors.
dc4eec1 @lifo Merge docrails:
lifo authored
396 # * AttributeAssignmentError - An error occurred while doing a mass assignment through the <tt>attributes=</tt> method.
d2fefbe @dhh Added MultiparameterAssignmentErrors and AttributeAssignmentError exc…
dhh authored
397 # You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error.
5707027 @dhh Added better exception error when unknown column types are used with …
dhh authored
398 #
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
399 # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
dc4eec1 @lifo Merge docrails:
lifo authored
400 # 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
401 # instances in the current object space.
402 class Base
dbbae5e @lifo Merge with docrails
lifo authored
403 ##
404 # :singleton-method:
db045db @dhh Initial
dhh authored
405 # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed
406 # 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 #7…
technoweenie authored
407 cattr_accessor :logger, :instance_writer => false
e694114 @jeremy Deprecation: removed Reloadable.
jeremy authored
408
db045db @dhh Initial
dhh authored
409 def self.inherited(child) #:nodoc:
410 @@subclasses[self] ||= []
411 @@subclasses[self] << child
412 super
413 end
e694114 @jeremy Deprecation: removed Reloadable.
jeremy authored
414
fed7d33 @dhh Fixed documentation
dhh authored
415 def self.reset_subclasses #:nodoc:
bfbf6bb @jamis Allow ARStore::Session to indicate that it should not be reloaded in …
jamis authored
416 nonreloadables = []
e7f61ea @jamis squash the memleak in dev mode finally (fingers crossed, here)
jamis authored
417 subclasses.each do |klass|
c08547d @josh Namespace Inflector, Dependencies, OrderedOptions, and TimeZone under…
josh authored
418 unless ActiveSupport::Dependencies.autoloaded? klass
bfbf6bb @jamis Allow ARStore::Session to indicate that it should not be reloaded in …
jamis authored
419 nonreloadables << klass
420 next
421 end
e7f61ea @jamis squash the memleak in dev mode finally (fingers crossed, here)
jamis authored
422 klass.instance_variables.each { |var| klass.send(:remove_instance_variable, var) }
423 klass.instance_methods(false).each { |m| klass.send :undef_method, m }
424 end
bfbf6bb @jamis Allow ARStore::Session to indicate that it should not be reloaded in …
jamis authored
425 @@subclasses = {}
426 nonreloadables.each { |klass| (@@subclasses[klass.superclass] ||= []) << klass }
3c0129a @dhh Fixed memory leak with Active Record classes when Dependencies.mechan…
dhh authored
427 end
428
db045db @dhh Initial
dhh authored
429 @@subclasses = {}
c3aa2bc @Manfred Ensure nested with_scope merges conditions inside out [#2193 state:re…
Manfred authored
430
dbbae5e @lifo Merge with docrails
lifo authored
431 ##
432 # :singleton-method:
a293278 @lifo Merge docrails
lifo authored
433 # Contains the database configuration - as is typically stored in config/database.yml -
434 # as a Hash.
435 #
436 # For example, the following database.yml...
437 #
438 # development:
439 # adapter: sqlite3
440 # database: db/development.sqlite3
441 #
442 # production:
443 # adapter: sqlite3
444 # database: db/production.sqlite3
445 #
446 # ...would result in ActiveRecord::Base.configurations to look like this:
447 #
448 # {
449 # 'development' => {
450 # 'adapter' => 'sqlite3',
451 # 'database' => 'db/development.sqlite3'
452 # },
453 # 'production' => {
454 # 'adapter' => 'sqlite3',
455 # 'database' => 'db/production.sqlite3'
456 # }
457 # }
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7…
technoweenie authored
458 cattr_accessor :configurations, :instance_writer => false
c4a3634 @jeremy Corrected @@configurations typo. #1410 [david@ruppconsulting.com]
jeremy authored
459 @@configurations = {}
460
dbbae5e @lifo Merge with docrails
lifo authored
461 ##
462 # :singleton-method:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
463 # 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
464 # :table_name_with_underscore. If the first is specified, the Product class will look for "productid" instead of "id" as
465 # 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
466 # that this is a global setting for all Active Records.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7…
technoweenie authored
467 cattr_accessor :primary_key_prefix_type, :instance_writer => false
db045db @dhh Initial
dhh authored
468 @@primary_key_prefix_type = nil
469
dbbae5e @lifo Merge with docrails
lifo authored
470 ##
471 # :singleton-method:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
472 # 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
473 # 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
474 # for tables in a shared database. By default, the prefix is the empty string.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7…
technoweenie authored
475 cattr_accessor :table_name_prefix, :instance_writer => false
db045db @dhh Initial
dhh authored
476 @@table_name_prefix = ""
477
dbbae5e @lifo Merge with docrails
lifo authored
478 ##
479 # :singleton-method:
db045db @dhh Initial
dhh authored
480 # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
481 # "people_basecamp"). By default, the suffix is the empty string.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7…
technoweenie authored
482 cattr_accessor :table_name_suffix, :instance_writer => false
db045db @dhh Initial
dhh authored
483 @@table_name_suffix = ""
484
dbbae5e @lifo Merge with docrails
lifo authored
485 ##
486 # :singleton-method:
84a14f2 @jeremy Raise ProtectedAttributeAssignmentError in development and test envir…
jeremy authored
487 # Indicates whether table names should be the pluralized versions of the corresponding class names.
98dc582 @lifo Merge docrails.
lifo authored
488 # 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
489 # See table_name for the full rules on table/class naming. This is true, by default.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7…
technoweenie authored
490 cattr_accessor :pluralize_table_names, :instance_writer => false
db045db @dhh Initial
dhh authored
491 @@pluralize_table_names = true
492
dbbae5e @lifo Merge with docrails
lifo authored
493 ##
494 # :singleton-method:
84a14f2 @jeremy Raise ProtectedAttributeAssignmentError in development and test envir…
jeremy authored
495 # Determines whether to use ANSI codes to colorize the logging statements committed by the connection adapter. These colors
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
496 # make it much easier to overview things during debugging (when used through a reader like +tail+ and on a black background), but
911614d @dhh Added ActiveRecord::Base.colorize_logging to control whether to use c…
dhh authored
497 # may complicate matters if you use software like syslog. This is true, by default.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7…
technoweenie authored
498 cattr_accessor :colorize_logging, :instance_writer => false
911614d @dhh Added ActiveRecord::Base.colorize_logging to control whether to use c…
dhh authored
499 @@colorize_logging = true
500
dbbae5e @lifo Merge with docrails
lifo authored
501 ##
502 # :singleton-method:
60de8c1 @dhh Added Base.default_timezone accessor that determines whether to use T…
dhh authored
503 # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates and times from the database.
504 # This is set to :local by default.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7…
technoweenie authored
505 cattr_accessor :default_timezone, :instance_writer => false
60de8c1 @dhh Added Base.default_timezone accessor that determines whether to use T…
dhh authored
506 @@default_timezone = :local
d8641ca @jeremy CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. …
jeremy authored
507
dbbae5e @lifo Merge with docrails
lifo authored
508 ##
509 # :singleton-method:
24c3599 @sstephenson Support using different database adapters for development and test wi…
sstephenson authored
510 # Specifies the format to use when dumping the database schema with Rails'
511 # Rakefile. If :sql, the schema is dumped as (potentially database-
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
512 # specific) SQL statements. If :ruby, the schema is dumped as an
24c3599 @sstephenson Support using different database adapters for development and test wi…
sstephenson authored
513 # ActiveRecord::Schema file which can be loaded into any database that
514 # supports migrations. Use :ruby if you want to have different database
515 # adapters for, e.g., your development and test environments.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7…
technoweenie authored
516 cattr_accessor :schema_format , :instance_writer => false
660952e @dhh CHANGED DEFAULT: ActiveRecord::Base.schema_format is now :ruby by def…
dhh authored
517 @@schema_format = :ruby
3b0e1d9 @josh Prefer string core_ext inflector methods over directly accessing Infl…
josh authored
518
dbbae5e @lifo Merge with docrails
lifo authored
519 ##
520 # :singleton-method:
bbab639 @nikz Set config.active_record.timestamped_migrations = false to have migra…
nikz authored
521 # Specify whether or not to use timestamps for migration numbers
522 cattr_accessor :timestamped_migrations , :instance_writer => false
523 @@timestamped_migrations = true
524
bca8751 @divoxx Add ActiveRecord option to store the full class name on STI's type co…
divoxx authored
525 # Determine whether to store the full constant name including namespace when using STI
526 superclass_delegating_accessor :store_full_sti_class
527 self.store_full_sti_class = false
3b0e1d9 @josh Prefer string core_ext inflector methods over directly accessing Infl…
josh authored
528
2530d0e @lifo Added default_scope to Base [#1381 state:committed] (Paweł Kondzior)
lifo authored
529 # Stores the default scope for the class
530 class_inheritable_accessor :default_scoping, :instance_writer => false
531 self.default_scoping = []
532
db045db @dhh Initial
dhh authored
533 class << self # Class methods
d5a4d5a @dhh Added ActiveRecord::Base.find(:last) (closes #11338) [miloops]
dhh authored
534 # Find operates with four different retrieval approaches:
7669011 @dhh Fixes for postgresql testing #1129, #1130, #1131
dhh authored
535 #
98dc582 @lifo Merge docrails.
lifo authored
536 # * Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]).
7669011 @dhh Fixes for postgresql testing #1129, #1130, #1131
dhh authored
537 # If no record can be found for all of the listed ids, then RecordNotFound will be raised.
98dc582 @lifo Merge docrails.
lifo authored
538 # * Find first - This will return the first record matched by the options used. These options can either be specific
539 # conditions or merely an order. If no record can be matched, +nil+ is returned. Use
540 # <tt>Model.find(:first, *args)</tt> or its shortcut <tt>Model.first(*args)</tt>.
541 # * Find last - This will return the last record matched by the options used. These options can either be specific
542 # conditions or merely an order. If no record can be matched, +nil+ is returned. Use
543 # <tt>Model.find(:last, *args)</tt> or its shortcut <tt>Model.last(*args)</tt>.
544 # * Find all - This will return all the records matched by the options used.
545 # If no records are found, an empty array is returned. Use
546 # <tt>Model.find(:all, *args)</tt> or its shortcut <tt>Model.all(*args)</tt>.
547 #
548 # All approaches accept an options hash as their last parameter.
549 #
a293278 @lifo Merge docrails
lifo authored
550 # ==== Parameters
98dc582 @lifo Merge docrails.
lifo authored
551 #
9cb5400 @lifo Merge docrails
lifo authored
552 # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1", <tt>[ "user_name = ?", username ]</tt>, or <tt>["user_name = :user_name", { :user_name => user_name }]</tt>. See conditions in the intro.
98dc582 @lifo Merge docrails.
lifo authored
553 # * <tt>:order</tt> - An SQL fragment like "created_at DESC, name".
554 # * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
97403ad @miloops Add :having option to find, to use in combination with grouped finds.…
miloops authored
555 # * <tt>:having</tt> - Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
98dc582 @lifo Merge docrails.
lifo authored
556 # * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned.
557 # * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5, it would skip rows 0 through 4.
39e1ac6 @lifo Merge docrails
lifo authored
558 # * <tt>:joins</tt> - Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed),
559 # named associations in the same form used for the <tt>:include</tt> option, which will perform an <tt>INNER JOIN</tt> on the associated table(s),
560 # or an array containing a mixture of both strings and named associations.
9661395 Remove references to nonexistent :joins documentation. Closes #10498 …
Marcel Molina authored
561 # If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns.
64092de @fxn Improve documentation coverage and markup
fxn authored
562 # Pass <tt>:readonly => false</tt> to override.
98dc582 @lifo Merge docrails.
lifo authored
563 # * <tt>:include</tt> - Names associations that should be loaded alongside. The symbols named refer
515886a @dhh Added documentation for new Base.find API and eager association loading
dhh authored
564 # to already defined associations. See eager loading under Associations.
98dc582 @lifo Merge docrails.
lifo authored
565 # * <tt>:select</tt> - By default, this is "*" as in "SELECT * FROM", but can be changed if you, for example, want to do a join but not
6ef3546 @lifo Merge docrails
lifo authored
566 # include the joined columns. Takes a string with the SELECT SQL fragment (e.g. "id, name").
98dc582 @lifo Merge docrails.
lifo authored
567 # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an alternate table name (or even the name
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
568 # of a database view).
98dc582 @lifo Merge docrails.
lifo authored
569 # * <tt>:readonly</tt> - Mark the returned records read-only so they cannot be saved or updated.
570 # * <tt>:lock</tt> - An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE".
64092de @fxn Improve documentation coverage and markup
fxn authored
571 # <tt>:lock => true</tt> gives connection's default exclusive lock, usually "FOR UPDATE".
7669011 @dhh Fixes for postgresql testing #1129, #1130, #1131
dhh authored
572 #
98dc582 @lifo Merge docrails.
lifo authored
573 # ==== Examples
574 #
575 # # find by id
db045db @dhh Initial
dhh authored
576 # Person.find(1) # returns the object for ID = 1
577 # Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
578 # Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobS…
Marcel Molina authored
579 # Person.find([1]) # returns an array for the object with ID = 1
515886a @dhh Added documentation for new Base.find API and eager association loading
dhh authored
580 # Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
581 #
1e9e198 @jeremy Note that find results may not be in the same order as the id argumen…
jeremy authored
582 # Note that returned records may not be in the same order as the ids you
64092de @fxn Improve documentation coverage and markup
fxn authored
583 # provide since database rows are unordered. Give an explicit <tt>:order</tt>
1e9e198 @jeremy Note that find results may not be in the same order as the id argumen…
jeremy authored
584 # to ensure the results are sorted.
585 #
98dc582 @lifo Merge docrails.
lifo authored
586 # ==== Examples
587 #
588 # # find first
7d01005 @dhh Fixed documentation and prepared for release of 0.12
dhh authored
589 # Person.find(:first) # returns the first object fetched by SELECT * FROM people
515886a @dhh Added documentation for new Base.find API and eager association loading
dhh authored
590 # Person.find(:first, :conditions => [ "user_name = ?", user_name])
9cb5400 @lifo Merge docrails
lifo authored
591 # Person.find(:first, :conditions => [ "user_name = :u", { :u => user_name }])
515886a @dhh Added documentation for new Base.find API and eager association loading
dhh authored
592 # Person.find(:first, :order => "created_on DESC", :offset => 5)
593 #
98dc582 @lifo Merge docrails.
lifo authored
594 # # find last
d5a4d5a @dhh Added ActiveRecord::Base.find(:last) (closes #11338) [miloops]
dhh authored
595 # Person.find(:last) # returns the last object fetched by SELECT * FROM people
596 # Person.find(:last, :conditions => [ "user_name = ?", user_name])
597 # Person.find(:last, :order => "created_on DESC", :offset => 5)
598 #
98dc582 @lifo Merge docrails.
lifo authored
599 # # find all
7d01005 @dhh Fixed documentation and prepared for release of 0.12
dhh authored
600 # Person.find(:all) # returns an array of objects for all the rows fetched by SELECT * FROM people
515886a @dhh Added documentation for new Base.find API and eager association loading
dhh authored
601 # Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50)
aa4af60 @lifo Improve documentation.
lifo authored
602 # Person.find(:all, :conditions => { :friends => ["Bob", "Steve", "Fred"] }
515886a @dhh Added documentation for new Base.find API and eager association loading
dhh authored
603 # Person.find(:all, :offset => 10, :limit => 10)
604 # Person.find(:all, :include => [ :account, :friends ])
3309268 @jeremy Add :group option, correspond to GROUP BY, to the find method and to …
jeremy authored
605 # Person.find(:all, :group => "category")
15aa6e0 @jeremy r4644@asus: jeremy | 2006-06-16 14:57:03 -0700
jeremy authored
606 #
98dc582 @lifo Merge docrails.
lifo authored
607 # Example for find with a lock: Imagine two concurrent transactions:
608 # each will read <tt>person.visits == 2</tt>, add 1 to it, and save, resulting
609 # in two saves of <tt>person.visits = 3</tt>. By locking the row, the second
15aa6e0 @jeremy r4644@asus: jeremy | 2006-06-16 14:57:03 -0700
jeremy authored
610 # transaction has to wait until the first is finished; we get the
98dc582 @lifo Merge docrails.
lifo authored
611 # expected <tt>person.visits == 4</tt>.
612 #
15aa6e0 @jeremy r4644@asus: jeremy | 2006-06-16 14:57:03 -0700
jeremy authored
613 # Person.transaction do
614 # person = Person.find(1, :lock => true)
615 # person.visits += 1
616 # person.save!
617 # end
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
618 def find(*args)
edd68a5 @dhh Refactored in use of extract_options! (closes #9079) [josh]
dhh authored
619 options = args.extract_options!
c9c1852 @dhh Making ActiveRecord faster [skaes]
dhh authored
620 validate_find_options(options)
621 set_readonly_option!(options)
64fcb75 @jeremy r3618@sedna: jeremy | 2005-10-14 12:06:03 -0700
jeremy authored
622
abc895b @dhh Added new Base.find API and deprecated find_all, find_first. Added pr…
dhh authored
623 case args.first
c9c1852 @dhh Making ActiveRecord faster [skaes]
dhh authored
624 when :first then find_initial(options)
d5a4d5a @dhh Added ActiveRecord::Base.find(:last) (closes #11338) [miloops]
dhh authored
625 when :last then find_last(options)
c9c1852 @dhh Making ActiveRecord faster [skaes]
dhh authored
626 when :all then find_every(options)
627 else find_from_ids(args, options)
db045db @dhh Initial
dhh authored
628 end
629 end
3b0e1d9 @josh Prefer string core_ext inflector methods over directly accessing Infl…
josh authored
630
98dc582 @lifo Merge docrails.
lifo authored
631 # A convenience wrapper for <tt>find(:first, *args)</tt>. You can pass in all the
632 # same arguments to this method as you can to <tt>find(:first)</tt>.
c6f2af5 @dhh Added ActiveRecord#Base.all/first/last as aliases for find(:all/:firs…
dhh authored
633 def first(*args)
634 find(:first, *args)
635 end
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
636
98dc582 @lifo Merge docrails.
lifo authored
637 # A convenience wrapper for <tt>find(:last, *args)</tt>. You can pass in all the
638 # same arguments to this method as you can to <tt>find(:last)</tt>.
c6f2af5 @dhh Added ActiveRecord#Base.all/first/last as aliases for find(:all/:firs…
dhh authored
639 def last(*args)
640 find(:last, *args)
641 end
3b0e1d9 @josh Prefer string core_ext inflector methods over directly accessing Infl…
josh authored
642
0a6980f Let Base.all use conditions etc like first/last
David Heinemeier Hansson authored
643 # This is an alias for find(:all). You can pass in all the same arguments to this method as you can
644 # to find(:all)
645 def all(*args)
646 find(:all, *args)
647 end
3b0e1d9 @josh Prefer string core_ext inflector methods over directly accessing Infl…
josh authored
648
98dc582 @lifo Merge docrails.
lifo authored
649 # 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
650 # be returned as an array with columns requested encapsulated as attributes of the model you call
a293278 @lifo Merge docrails
lifo authored
651 # this method from. If you call <tt>Product.find_by_sql</tt> then the results will be returned in
652 # 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
653 #
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
654 # If you call a complicated SQL query which spans multiple tables the columns specified by the
655 # 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
656 # table.
657 #
98dc582 @lifo Merge docrails.
lifo authored
658 # 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
659 # no database agnostic conversions performed. This should be a last resort because using, for example,
660 # MySQL specific terms will lock you to using that particular database engine or require you to
a293278 @lifo Merge docrails
lifo authored
661 # change your call if you switch engines.
edf32ce More complete documentation for find_by_sql. Closes #7912 [fearoffish]
Marcel Molina authored
662 #
663 # ==== Examples
98dc582 @lifo Merge docrails.
lifo authored
664 # # A simple SQL query spanning multiple tables
edf32ce More complete documentation for find_by_sql. Closes #7912 [fearoffish]
Marcel Molina authored
665 # Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
666 # > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
667 #
668 # # You can use the same string replacement techniques as you can with ActiveRecord#find
669 # Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
670 # > [#<Post:0x36bff9c @attributes={"first_name"=>"The Cheap Man Buys Twice"}>, ...]
db045db @dhh Initial
dhh authored
671 def find_by_sql(sql)
6e3d2a7 @jeremy Revert "Performance: freeze cached rows instead of duping"
jeremy authored
672 connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) }
db045db @dhh Initial
dhh authored
673 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
674
dbbae5e @lifo Merge with docrails
lifo authored
675 # Returns true if a record exists in the table that matches the +id+ or
5a8f764 @smtlaissezfaire Add ActiveRecord::Base.exists? with no args [#1817 state:committed]
smtlaissezfaire authored
676 # conditions given, or false otherwise. The argument can take five forms:
dbbae5e @lifo Merge with docrails
lifo authored
677 #
678 # * Integer - Finds the record with this primary key.
679 # * String - Finds the record with a primary key corresponding to this
680 # string (such as <tt>'5'</tt>).
681 # * Array - Finds the record that matches these +find+-style conditions
682 # (such as <tt>['color = ?', 'red']</tt>).
683 # * Hash - Finds the record that matches these +find+-style conditions
684 # (such as <tt>{:color => 'red'}</tt>).
5a8f764 @smtlaissezfaire Add ActiveRecord::Base.exists? with no args [#1817 state:committed]
smtlaissezfaire authored
685 # * No args - Returns false if the table is empty, true otherwise.
971ed15 Document API for exists?'s parameter and provide examples of usage. C…
Marcel Molina authored
686 #
dbbae5e @lifo Merge with docrails
lifo authored
687 # For more information about specifying conditions as a Hash or Array,
688 # see the Conditions section in the introduction to ActiveRecord::Base.
971ed15 Document API for exists?'s parameter and provide examples of usage. C…
Marcel Molina authored
689 #
dbbae5e @lifo Merge with docrails
lifo authored
690 # Note: You can't pass in a condition as a string (like <tt>name =
691 # 'Jamie'</tt>), since it would be sanitized and then queried against
692 # the primary key column, like <tt>id = 'name = \'Jamie\''</tt>.
971ed15 Document API for exists?'s parameter and provide examples of usage. C…
Marcel Molina authored
693 #
694 # ==== Examples
abc895b @dhh Added new Base.find API and deprecated find_all, find_first. Added pr…
dhh authored
695 # Person.exists?(5)
58ebf30 @jeremy The exists? class method should treat a string argument as an id rath…
jeremy authored
696 # Person.exists?('5')
8085cbf @dhh Added support for conditions on Base.exists? (closes #5689) [josh@jos…
dhh authored
697 # Person.exists?(:name => "David")
58ebf30 @jeremy The exists? class method should treat a string argument as an id rath…
jeremy authored
698 # Person.exists?(['name LIKE ?', "%#{query}%"])
5a8f764 @smtlaissezfaire Add ActiveRecord::Base.exists? with no args [#1817 state:committed]
smtlaissezfaire authored
699 # Person.exists?
700 def exists?(id_or_conditions = {})
afcbdfc Changed ActiveRecord::Base#exists? to invoke find_initial so that it …
Peter Marklund authored
701 find_initial(
702 :select => "#{quoted_table_name}.#{primary_key}",
703 :conditions => expand_id_conditions(id_or_conditions)) ? true : false
db045db @dhh Initial
dhh authored
704 end
abc895b @dhh Added new Base.find API and deprecated find_all, find_first. Added pr…
dhh authored
705
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
706 # Creates an object (or multiple objects) and saves it to the database, if validations pass.
a23bea7 Document API for create's attributes parameter and provide examples. …
Marcel Molina authored
707 # The resulting object is returned whether the object was saved successfully to the database or not.
708 #
709 # The +attributes+ parameter can be either be a Hash or an Array of Hashes. These Hashes describe the
710 # attributes on the objects that are to be created.
711 #
712 # ==== Examples
713 # # Create a single new object
714 # User.create(:first_name => 'Jamie')
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new alrea…
dhh authored
715 #
a23bea7 Document API for create's attributes parameter and provide examples. …
Marcel Molina authored
716 # # Create an Array of new objects
dc4eec1 @lifo Merge docrails:
lifo authored
717 # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new alrea…
dhh authored
718 #
719 # # Create a single object and pass it into a block to set other attributes.
720 # User.create(:first_name => 'Jamie') do |u|
721 # u.is_admin = false
722 # end
723 #
724 # # Creating an Array of new objects using a block, where the block is executed for each object:
dc4eec1 @lifo Merge docrails:
lifo authored
725 # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u|
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new alrea…
dhh authored
726 # u.is_admin = false
3b0e1d9 @josh Prefer string core_ext inflector methods over directly accessing Infl…
josh authored
727 # end
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new alrea…
dhh authored
728 def create(attributes = nil, &block)
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#…
dhh authored
729 if attributes.is_a?(Array)
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new alrea…
dhh authored
730 attributes.collect { |attr| create(attr, &block) }
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#…
dhh authored
731 else
732 object = new(attributes)
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new alrea…
dhh authored
733 yield(object) if block_given?
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#…
dhh authored
734 object.save
735 object
736 end
db045db @dhh Initial
dhh authored
737 end
738
1b7a18d Document options and add examples for update. Closes #7985 [fearoffish]
Marcel Molina authored
739 # Updates an object (or multiple objects) and saves it to the database, if validations pass.
740 # The resulting object is returned whether the object was saved successfully to the database or not.
5e99422 @dhh Updated docs (closes #3799) [ruby@bobsilva.com]
dhh authored
741 #
a293278 @lifo Merge docrails
lifo authored
742 # ==== Parameters
5e99422 @dhh Updated docs (closes #3799) [ruby@bobsilva.com]
dhh authored
743 #
dc4eec1 @lifo Merge docrails:
lifo authored
744 # * +id+ - This should be the id or an array of ids to be updated.
18eb80c @lifo Merge docrails
lifo authored
745 # * +attributes+ - This should be a hash of attributes to be set on the object, or an array of hashes.
1b7a18d Document options and add examples for update. Closes #7985 [fearoffish]
Marcel Molina authored
746 #
747 # ==== Examples
748 #
749 # # Updating one record:
18eb80c @lifo Merge docrails
lifo authored
750 # Person.update(15, :user_name => 'Samuel', :group => 'expert')
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
751 #
1b7a18d Document options and add examples for update. Closes #7985 [fearoffish]
Marcel Molina authored
752 # # Updating multiple records:
dc4eec1 @lifo Merge docrails:
lifo authored
753 # people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
5e99422 @dhh Updated docs (closes #3799) [ruby@bobsilva.com]
dhh authored
754 # Person.update(people.keys, people.values)
db045db @dhh Initial
dhh authored
755 def update(id, attributes)
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#…
dhh authored
756 if id.is_a?(Array)
757 idx = -1
8b5f4e4 @jeremy Ruby 1.9 compat: fix warnings, shadowed block vars, and unitialized i…
jeremy authored
758 id.collect { |one_id| idx += 1; update(one_id, attributes[idx]) }
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#…
dhh authored
759 else
760 object = find(id)
761 object.update_attributes(attributes)
762 object
763 end
db045db @dhh Initial
dhh authored
764 end
765
39e1ac6 @lifo Merge docrails
lifo authored
766 # Deletes the row with a primary key matching the +id+ argument, using a
767 # SQL +DELETE+ statement, and returns the number of rows deleted. Active
768 # Record objects are not instantiated, so the object's callbacks are not
769 # executed, including any <tt>:dependent</tt> association options or
770 # Observer methods.
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
771 #
39e1ac6 @lifo Merge docrails
lifo authored
772 # You can delete multiple rows at once by passing an Array of <tt>id</tt>s.
6a45e01 Document options and add examples for delete. Closes #7986 [fearoffish]
Marcel Molina authored
773 #
39e1ac6 @lifo Merge docrails
lifo authored
774 # Note: Although it is often much faster than the alternative,
775 # <tt>#destroy</tt>, skipping callbacks might bypass business logic in
776 # your application that ensures referential integrity or performs other
777 # essential jobs.
6a45e01 Document options and add examples for delete. Closes #7986 [fearoffish]
Marcel Molina authored
778 #
779 # ==== Examples
780 #
39e1ac6 @lifo Merge docrails
lifo authored
781 # # Delete a single row
6a45e01 Document options and add examples for delete. Closes #7986 [fearoffish]
Marcel Molina authored
782 # Todo.delete(1)
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
783 #
39e1ac6 @lifo Merge docrails
lifo authored
784 # # Delete multiple rows
785 # Todo.delete([2,3,4])
648b8fd @dhh Added Base.destroy and Base.delete to remove records without holding …
dhh authored
786 def delete(id)
98165fd @jeremy Consistently quote primary key column names. Closes #7763.
jeremy authored
787 delete_all([ "#{connection.quote_column_name(primary_key)} IN (?)", id ])
648b8fd @dhh Added Base.destroy and Base.delete to remove records without holding …
dhh authored
788 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
789
ed69b38 Document options and add examples for destroy. Closes #7988 [fearoffish]
Marcel Molina authored
790 # Destroy an object (or multiple objects) that has the given id, the object is instantiated first,
791 # therefore all callbacks and filters are fired off before the object is deleted. This method is
792 # less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
793 #
794 # This essentially finds the object (or multiple objects) with the given id, creates a new object
ed69b38 Document options and add examples for destroy. Closes #7988 [fearoffish]
Marcel Molina authored
795 # from the attributes, and then calls destroy on it.
796 #
a293278 @lifo Merge docrails
lifo authored
797 # ==== Parameters
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
798 #
dc4eec1 @lifo Merge docrails:
lifo authored
799 # * +id+ - Can be either an Integer or an Array of Integers.
ed69b38 Document options and add examples for destroy. Closes #7988 [fearoffish]
Marcel Molina authored
800 #
801 # ==== Examples
802 #
803 # # Destroy a single object
804 # Todo.destroy(1)
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
805 #
ed69b38 Document options and add examples for destroy. Closes #7988 [fearoffish]
Marcel Molina authored
806 # # Destroy multiple objects
807 # todos = [1,2,3]
808 # Todo.destroy(todos)
648b8fd @dhh Added Base.destroy and Base.delete to remove records without holding …
dhh authored
809 def destroy(id)
8b5f4e4 @jeremy Ruby 1.9 compat: fix warnings, shadowed block vars, and unitialized i…
jeremy authored
810 if id.is_a?(Array)
811 id.map { |one_id| destroy(one_id) }
812 else
813 find(id).destroy
814 end
648b8fd @dhh Added Base.destroy and Base.delete to remove records without holding …
dhh authored
815 end
816
4f1d353 Document options and add examples for update_all. Closes #7990 [fearo…
Marcel Molina authored
817 # Updates all records with details given if they match a set of conditions supplied, limits and order can
6ef3546 @lifo Merge docrails
lifo authored
818 # also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the
f97832b @lifo Merge docrails
lifo authored
819 # database. It does not instantiate the involved models and it does not trigger Active Record callbacks
820 # or validations.
a38f28f @jeremy Base.update_all :order and :limit options. Useful for MySQL updates t…
jeremy authored
821 #
a293278 @lifo Merge docrails
lifo authored
822 # ==== Parameters
4f1d353 Document options and add examples for update_all. Closes #7990 [fearo…
Marcel Molina authored
823 #
f97832b @lifo Merge docrails
lifo authored
824 # * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
825 # * +conditions+ - A string, array, or hash representing the WHERE part of an SQL statement. See conditions in the intro.
6ef3546 @lifo Merge docrails
lifo authored
826 # * +options+ - Additional options are <tt>:limit</tt> and <tt>:order</tt>, see the examples for usage.
4f1d353 Document options and add examples for update_all. Closes #7990 [fearo…
Marcel Molina authored
827 #
828 # ==== Examples
829 #
f97832b @lifo Merge docrails
lifo authored
830 # # Update all customers with the given attributes
831 # Customer.update_all :wants_email => true
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
832 #
f97832b @lifo Merge docrails
lifo authored
833 # # Update all books with 'Rails' in their title
834 # Book.update_all "author = 'David'", "title LIKE '%Rails%'"
4f1d353 Document options and add examples for update_all. Closes #7990 [fearo…
Marcel Molina authored
835 #
f97832b @lifo Merge docrails
lifo authored
836 # # Update all avatars migrated more than a week ago
837 # Avatar.update_all ['migrated_at = ?, Time.now.utc], ['migrated_at > ?', 1.week.ago]
838 #
839 # # Update all books that match our conditions, but limit it to 5 ordered by date
840 # Book.update_all "author = 'David'", "title LIKE '%Rails%'", :order => 'created_at', :limit => 5
a38f28f @jeremy Base.update_all :order and :limit options. Useful for MySQL updates t…
jeremy authored
841 def update_all(updates, conditions = nil, options = {})
ebe3a0d @jeremy More thoroughly quote table names. Exposes some issues with sqlite2 a…
jeremy authored
842 sql = "UPDATE #{quoted_table_name} SET #{sanitize_sql_for_assignment(updates)} "
7c9851d @tarmo Support :limit on update_all so that has_many with :limit can be safe…
tarmo authored
843
a38f28f @jeremy Base.update_all :order and :limit options. Useful for MySQL updates t…
jeremy authored
844 scope = scope(:find)
7c9851d @tarmo Support :limit on update_all so that has_many with :limit can be safe…
tarmo authored
845
846 select_sql = ""
847 add_conditions!(select_sql, conditions, scope)
848
849 if options.has_key?(:limit) || (scope && scope[:limit])
850 # Only take order from scope if limit is also provided by scope, this
851 # is useful for updating a has_many association with a limit.
852 add_order!(select_sql, options[:order], scope)
853
854 add_limit!(select_sql, options, scope)
855 sql.concat(connection.limited_update_conditions(select_sql, quoted_table_name, connection.quote_column_name(primary_key)))
856 else
857 add_order!(select_sql, options[:order], nil)
858 sql.concat(select_sql)
859 end
860
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
861 connection.update(sql, "#{name} Update")
db045db @dhh Initial
dhh authored
862 end
0d2db8a @dhh Added Base.update_collection that can update an array of id/attribute…
dhh authored
863
39e1ac6 @lifo Merge docrails
lifo authored
864 # Destroys the records matching +conditions+ by instantiating each
865 # record and calling its +destroy+ method. Each object's callbacks are
866 # executed (including <tt>:dependent</tt> association options and
867 # +before_destroy+/+after_destroy+ Observer methods). Returns the
868 # collection of objects that were destroyed; each will be frozen, to
869 # reflect that no changes should be made (since they can't be
870 # persisted).
871 #
872 # Note: Instantiation, callback execution, and deletion of each
873 # record can be time consuming when you're removing many records at
874 # once. It generates at least one SQL +DELETE+ query per record (or
875 # possibly more, to enforce your callbacks). If you want to delete many
876 # rows quickly, without concern for their associations or callbacks, use
877 # +delete_all+ instead.
4b055a4 @jeremy Update destroy_all and delete_all documentation to better describe th…
jeremy authored
878 #
a293278 @lifo Merge docrails
lifo authored
879 # ==== Parameters
4b055a4 @jeremy Update destroy_all and delete_all documentation to better describe th…
jeremy authored
880 #
39e1ac6 @lifo Merge docrails
lifo authored
881 # * +conditions+ - A string, array, or hash that specifies which records
882 # to destroy. If omitted, all records are destroyed. See the
883 # Conditions section in the introduction to ActiveRecord::Base for
884 # more information.
4b055a4 @jeremy Update destroy_all and delete_all documentation to better describe th…
jeremy authored
885 #
39e1ac6 @lifo Merge docrails
lifo authored
886 # ==== Examples
4b055a4 @jeremy Update destroy_all and delete_all documentation to better describe th…
jeremy authored
887 #
a293278 @lifo Merge docrails
lifo authored
888 # Person.destroy_all("last_login < '2004-04-04'")
39e1ac6 @lifo Merge docrails
lifo authored
889 # Person.destroy_all(:status => "inactive")
db045db @dhh Initial
dhh authored
890 def destroy_all(conditions = nil)
3dfa56c @dhh Updated all references to the old find_first and find_all to use the …
dhh authored
891 find(:all, :conditions => conditions).each { |object| object.destroy }
db045db @dhh Initial
dhh authored
892 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
893
4b055a4 @jeremy Update destroy_all and delete_all documentation to better describe th…
jeremy authored
894 # Deletes the records matching +conditions+ without instantiating the records first, and hence not
6ef3546 @lifo Merge docrails
lifo authored
895 # calling the +destroy+ method nor invoking callbacks. This is a single SQL DELETE statement that
a293278 @lifo Merge docrails
lifo authored
896 # goes straight to the database, much more efficient than +destroy_all+. Be careful with relations
53cd102 @lifo Merge with docrails
lifo authored
897 # though, in particular <tt>:dependent</tt> rules defined on associations are not honored. Returns
898 # the number of rows affected.
4b055a4 @jeremy Update destroy_all and delete_all documentation to better describe th…
jeremy authored
899 #
a293278 @lifo Merge docrails
lifo authored
900 # ==== Parameters
4b055a4 @jeremy Update destroy_all and delete_all documentation to better describe th…
jeremy authored
901 #
dc4eec1 @lifo Merge docrails:
lifo authored
902 # * +conditions+ - Conditions are specified the same way as with +find+ method.
4b055a4 @jeremy Update destroy_all and delete_all documentation to better describe th…
jeremy authored
903 #
904 # ==== Example
905 #
a293278 @lifo Merge docrails
lifo authored
906 # Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
907 # Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
4b055a4 @jeremy Update destroy_all and delete_all documentation to better describe th…
jeremy authored
908 #
a293278 @lifo Merge docrails
lifo authored
909 # Both calls delete the affected posts all at once with a single DELETE statement. If you need to destroy dependent
6ef3546 @lifo Merge docrails
lifo authored
910 # associations or call your <tt>before_*</tt> or +after_destroy+ callbacks, use the +destroy_all+ method instead.
db045db @dhh Initial
dhh authored
911 def delete_all(conditions = nil)
9b6207c @jeremy Quote table names. Defaults to column quoting. Closes #4593.
jeremy authored
912 sql = "DELETE FROM #{quoted_table_name} "
c9c1852 @dhh Making ActiveRecord faster [skaes]
dhh authored
913 add_conditions!(sql, conditions, scope(:find))
db045db @dhh Initial
dhh authored
914 connection.delete(sql, "#{name} Delete all")
915 end
916
917 # 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
918 # 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
919 # using the ActiveRecord::Calculations class methods. Look into those before using this.
920 #
a293278 @lifo Merge docrails
lifo authored
921 # ==== Parameters
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
922 #
dc4eec1 @lifo Merge docrails:
lifo authored
923 # * +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
924 #
925 # ==== Examples
926 #
e17bf81 @jamis Fix typo in count_by_sql documentation #1969 [Alexey Verkhovsky]
jamis authored
927 # Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
db045db @dhh Initial
dhh authored
928 def count_by_sql(sql)
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in r…
dhh authored
929 sql = sanitize_conditions(sql)
caaf40d @dhh Added AbstractAdapter#select_value and AbstractAdapter#select_values …
dhh authored
930 connection.select_value(sql, "#{name} Count").to_i
db045db @dhh Initial
dhh authored
931 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
932
8375237 @jamis Made increment_counter/decrement_counter play nicely with optimistic …
jamis authored
933 # A generic "counter updater" implementation, intended primarily to be
934 # used by increment_counter and decrement_counter, but which may also
935 # be useful on its own. It simply does a direct SQL update for the record
936 # with the given ID, altering the given hash of counters by the amount
937 # given by the corresponding value:
938 #
a293278 @lifo Merge docrails
lifo authored
939 # ==== Parameters
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
940 #
7487196 @lifo Add array id support to Model.update_counters. [#1254 state:resolved]…
lifo authored
941 # * +id+ - The id of the object you wish to update a counter on or an Array of ids.
dc4eec1 @lifo Merge docrails:
lifo authored
942 # * +counters+ - An Array of Hashes containing the names of the fields
943 # to update as keys and the amount to update the field by as values.
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
944 #
6bd7d30 Document options for update_counters. Closes #8091 [fearoffish]
Marcel Molina authored
945 # ==== Examples
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
946 #
947 # # 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
948 # # increment the action_count by 1
8375237 @jamis Made increment_counter/decrement_counter play nicely with optimistic …
jamis authored
949 # Post.update_counters 5, :comment_count => -1, :action_count => 1
6bd7d30 Document options for update_counters. Closes #8091 [fearoffish]
Marcel Molina authored
950 # # Executes the following SQL:
8375237 @jamis Made increment_counter/decrement_counter play nicely with optimistic …
jamis authored
951 # # UPDATE posts
952 # # SET comment_count = comment_count - 1,
953 # # action_count = action_count + 1
954 # # WHERE id = 5
7487196 @lifo Add array id support to Model.update_counters. [#1254 state:resolved]…
lifo authored
955 #
956 # # For the Posts with id of 10 and 15, increment the comment_count by 1
957 # Post.update_counters [10, 15], :comment_count => 1
958 # # Executes the following SQL:
959 # # UPDATE posts
960 # # SET comment_count = comment_count + 1,
961 # # WHERE id IN (10, 15)
8375237 @jamis Made increment_counter/decrement_counter play nicely with optimistic …
jamis authored
962 def update_counters(id, counters)
963 updates = counters.inject([]) { |list, (counter_name, increment)|
964 sign = increment < 0 ? "-" : "+"
459e581 @miloops update_counters should update nil values.
miloops authored
965 list << "#{connection.quote_column_name(counter_name)} = COALESCE(#{connection.quote_column_name(counter_name)}, 0) #{sign} #{increment.abs}"
8375237 @jamis Made increment_counter/decrement_counter play nicely with optimistic …
jamis authored
966 }.join(", ")
7487196 @lifo Add array id support to Model.update_counters. [#1254 state:resolved]…
lifo authored
967
968 if id.is_a?(Array)
969 ids_list = id.map {|i| quote_value(i)}.join(', ')
970 condition = "IN (#{ids_list})"
971 else
972 condition = "= #{quote_value(id)}"
973 end
974
975 update_all(updates, "#{connection.quote_column_name(primary_key)} #{condition}")
8375237 @jamis Made increment_counter/decrement_counter play nicely with optimistic …
jamis authored
976 end
977
15dc567 Also add documentation enhancements for increment_counter. Closes #80…
Marcel Molina authored
978 # Increment a number field by one, usually representing a count.
979 #
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
980 # This is used for caching aggregate values, so that they don't need to be computed every time.
981 # For example, a DiscussionBoard may cache post_count and comment_count otherwise every time the board is
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobS…
Marcel Molina authored
982 # 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 #80…
Marcel Molina authored
983 #
a293278 @lifo Merge docrails
lifo authored
984 # ==== Parameters
15dc567 Also add documentation enhancements for increment_counter. Closes #80…
Marcel Molina authored
985 #
dc4eec1 @lifo Merge docrails:
lifo authored
986 # * +counter_name+ - The name of the field that should be incremented.
987 # * +id+ - The id of the object that should be incremented.
15dc567 Also add documentation enhancements for increment_counter. Closes #80…
Marcel Molina authored
988 #
989 # ==== Examples
990 #
991 # # Increment the post_count column for the record with an id of 5
992 # DiscussionBoard.increment_counter(:post_count, 5)
db045db @dhh Initial
dhh authored
993 def increment_counter(counter_name, id)
8375237 @jamis Made increment_counter/decrement_counter play nicely with optimistic …
jamis authored
994 update_counters(id, counter_name => 1)
db045db @dhh Initial
dhh authored
995 end
996
5bd3570 Enhance documentation for decrement_counter. Closes #8093. [fearoffish]
Marcel Molina authored
997 # Decrement a number field by one, usually representing a count.
998 #
999 # This works the same as increment_counter but reduces the column value by 1 instead of increasing it.
1000 #
a293278 @lifo Merge docrails
lifo authored
1001 # ==== Parameters
5bd3570 Enhance documentation for decrement_counter. Closes #8093. [fearoffish]
Marcel Molina authored
1002 #
dc4eec1 @lifo Merge docrails:
lifo authored
1003 # * +counter_name+ - The name of the field that should be decremented.
1004 # * +id+ - The id of the object that should be decremented.
5bd3570 Enhance documentation for decrement_counter. Closes #8093. [fearoffish]
Marcel Molina authored
1005 #
1006 # ==== Examples
1007 #
1008 # # Decrement the post_count column for the record with an id of 5
1009 # DiscussionBoard.decrement_counter(:post_count, 5)
db045db @dhh Initial
dhh authored
1010 def decrement_counter(counter_name, id)
8375237 @jamis Made increment_counter/decrement_counter play nicely with optimistic …
jamis authored
1011 update_counters(id, counter_name => -1)
db045db @dhh Initial
dhh authored
1012 end
1013
98dc582 @lifo Merge docrails.
lifo authored
1014 # Attributes named in this macro are protected from mass-assignment,
1015 # such as <tt>new(attributes)</tt>,
1016 # <tt>update_attributes(attributes)</tt>, or
1017 # <tt>attributes=(attributes)</tt>.
1018 #
1019 # Mass-assignment to these attributes will simply be ignored, to assign
1020 # to them you can use direct writer methods. This is meant to protect
1021 # sensitive attributes from being overwritten by malicious users
1022 # tampering with URLs or forms.
db045db @dhh Initial
dhh authored
1023 #
1024 # class Customer < ActiveRecord::Base
1025 # attr_protected :credit_rating
1026 # end
1027 #
1028 # customer = Customer.new("name" => David, "credit_rating" => "Excellent")
1029 # customer.credit_rating # => nil
1030 # customer.attributes = { "description" => "Jolly fellow", "credit_rating" => "Superb" }
1031 # customer.credit_rating # => nil
1032 #
1033 # customer.credit_rating = "Average"
1034 # customer.credit_rating # => "Average"
d761ac4 Add docs explaining how to protect all attributes using attr_accessib…
Marcel Molina authored
1035 #
98dc582 @lifo Merge docrails.
lifo authored
1036 # To start from an all-closed default and enable attributes as needed,
1037 # have a look at +attr_accessible+.
db045db @dhh Initial
dhh authored
1038 def attr_protected(*attributes)
b6bac73 Merge commit 'origin/master'
Yehuda Katz + Carl Lerche authored
1039 write_inheritable_attribute(:attr_protected, Set.new(attributes.map {|a| a.to_s}) + (protected_attributes || []))
db045db @dhh Initial
dhh authored
1040 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
1041
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
1042 # Returns an array of all the attributes that have been protected from mass-assignment.
db045db @dhh Initial
dhh authored
1043 def protected_attributes # :nodoc:
288e947 @clemens Some performance goodness for inheritable attributes.
clemens authored
1044 read_inheritable_attribute(:attr_protected)
db045db @dhh Initial
dhh authored
1045 end
1046
98dc582 @lifo Merge docrails.
lifo authored
1047 # Specifies a white list of model attributes that can be set via
1048 # mass-assignment, such as <tt>new(attributes)</tt>,
1049 # <tt>update_attributes(attributes)</tt>, or
1050 # <tt>attributes=(attributes)</tt>
f770b82 Enhance explanation with more examples for attr_accessible macro. Clo…
Marcel Molina authored
1051 #
98dc582 @lifo Merge docrails.
lifo authored
1052 # This is the opposite of the +attr_protected+ macro: Mass-assignment
1053 # will only set attributes in this list, to assign to the rest of
1054 # attributes you can use direct writer methods. This is meant to protect
1055 # sensitive attributes from being overwritten by malicious users
1056 # tampering with URLs or forms. If you'd rather start from an all-open
1057 # default and restrict attributes as needed, have a look at
1058 # +attr_protected+.
d761ac4 Add docs explaining how to protect all attributes using attr_accessib…
Marcel Molina authored
1059 #
1060 # class Customer < ActiveRecord::Base
f770b82 Enhance explanation with more examples for attr_accessible macro. Clo…
Marcel Molina authored
1061 # attr_accessible :name, :nickname
d761ac4 Add docs explaining how to protect all attributes using attr_accessib…
Marcel Molina authored
1062 # end
1063 #
f770b82 Enhance explanation with more examples for attr_accessible macro. Clo…
Marcel Molina authored
1064 # customer = Customer.new(:name => "David", :nickname => "Dave", :credit_rating => "Excellent")
1065 # customer.credit_rating # => nil
1066 # customer.attributes = { :name => "Jolly fellow", :credit_rating => "Superb" }
1067 # customer.credit_rating # => nil
d761ac4 Add docs explaining how to protect all attributes using attr_accessib…
Marcel Molina authored
1068 #
f770b82 Enhance explanation with more examples for attr_accessible macro. Clo…
Marcel Molina authored
1069 # customer.credit_rating = "Average"
1070 # customer.credit_rating # => "Average"
db045db @dhh Initial
dhh authored