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