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