Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100755 3126 lines (2817 sloc) 137.45 kb
db045db David Heinemeier Hansson Initial
dhh authored
1 require 'yaml'
aabf909 Jeremy Kemper Correct reader method generation for primary key attribute: handle case ...
jeremy authored
2 require 'set'
db045db David Heinemeier Hansson Initial
dhh authored
3
4 module ActiveRecord #:nodoc:
98dc582 Pratik Merge docrails.
lifo authored
5 # Generic Active Record exception class.
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
6 class ActiveRecordError < StandardError
db045db David Heinemeier Hansson Initial
dhh authored
7 end
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
8
0432d15 Pratik Merge with docrails.
lifo authored
9 # Raised when the single-table inheritance mechanism fails to locate the subclass
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
10 # (for example due to improper usage of column that +inheritance_column+ points to).
605bc77 David Heinemeier Hansson Added a better exception for when a type column is used in a table witho...
dhh authored
11 class SubclassNotFound < ActiveRecordError #:nodoc:
12 end
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
13
64092de Xavier Noria Improve documentation coverage and markup
fxn authored
14 # Raised when an object assigned to an association has an incorrect type.
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
15 #
64092de Xavier Noria Improve documentation coverage and markup
fxn authored
16 # class Ticket < ActiveRecord::Base
17 # has_many :patches
18 # end
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
19 #
64092de Xavier Noria Improve documentation coverage and markup
fxn authored
20 # class Patch < ActiveRecord::Base
21 # belongs_to :ticket
22 # end
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
23 #
64092de Xavier Noria Improve documentation coverage and markup
fxn authored
24 # # Comments are not patches, this assignment raises AssociationTypeMismatch.
25 # @ticket.patches << Comment.new(:content => "Please attach tests to your patch.")
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
26 class AssociationTypeMismatch < ActiveRecordError
db045db David Heinemeier Hansson Initial
dhh authored
27 end
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
28
29 # Raised when unserialized object's type mismatches one specified for serializable field.
30 class SerializationTypeMismatch < ActiveRecordError
db045db David Heinemeier Hansson Initial
dhh authored
31 end
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
32
98dc582 Pratik Merge docrails.
lifo authored
33 # Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt> misses adapter field).
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
34 class AdapterNotSpecified < ActiveRecordError
db045db David Heinemeier Hansson Initial
dhh authored
35 end
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
36
98dc582 Pratik Merge docrails.
lifo authored
37 # Raised when Active Record cannot find database adapter specified in <tt>config/database.yml</tt> or programmatically.
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
38 class AdapterNotFound < ActiveRecordError
db045db David Heinemeier Hansson Initial
dhh authored
39 end
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
40
98dc582 Pratik Merge docrails.
lifo authored
41 # Raised when connection to the database could not been established (for example when <tt>connection=</tt> is given a nil object).
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
42 class ConnectionNotEstablished < ActiveRecordError
db045db David Heinemeier Hansson Initial
dhh authored
43 end
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
44
98dc582 Pratik Merge docrails.
lifo authored
45 # Raised when Active Record cannot find record by given id or set of ids.
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
46 class RecordNotFound < ActiveRecordError
db045db David Heinemeier Hansson Initial
dhh authored
47 end
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
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 David Heinemeier Hansson Fixed that Base.save should always return false if the save didn't succe...
dhh authored
52 end
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
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 David Heinemeier Hansson Initial
dhh authored
56 end
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
57
64092de Xavier Noria Improve documentation coverage and markup
fxn authored
58 # Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example, when using +find+ method)
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
59 # does not match number of expected variables.
60 #
64092de Xavier Noria Improve documentation coverage and markup
fxn authored
61 # For example, in
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
62 #
64092de Xavier Noria Improve documentation coverage and markup
fxn authored
63 # Location.find :all, :conditions => ["lat = ? AND lng = ?", 53.7362]
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
64 #
64092de Xavier Noria Improve documentation coverage and markup
fxn authored
65 # two placeholders are given but only one variable to fill them.
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
66 class PreparedStatementInvalid < ActiveRecordError
554597d David Heinemeier Hansson Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
67 end
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
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 Pratik Merge docrails.
lifo authored
73 # Read more about optimistic locking in ActiveRecord::Locking module RDoc.
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
74 class StaleObjectError < ActiveRecordError
fbf9281 David Heinemeier Hansson Added automated optimistic locking if the field lock_version is present ...
dhh authored
75 end
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
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 David Heinemeier Hansson Added support for limit and offset with eager loading of has_one and bel...
dhh authored
80 end
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
81
82 # Raised on attempt to update record that is instantiated as read only.
83 class ReadOnlyRecord < ActiveRecordError
64fcb75 Jeremy Kemper r3618@sedna: jeremy | 2005-10-14 12:06:03 -0700
jeremy authored
84 end
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
85
6e75455 Pratik Merge docrails changes
lifo authored
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 Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
113 class Rollback < ActiveRecordError
5b2e8b1 risk danger olson Fix that ActiveRecord would create attribute methods and override custom...
technoweenie authored
114 end
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
115
98dc582 Pratik Merge docrails.
lifo authored
116 # Raised when attribute has a name reserved by Active Record (when attribute has name of one of Active Record instance methods).
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
117 class DangerousAttributeError < ActiveRecordError
ebbe4fb Michael Koziarski Replace the transaction {|transaction|..} semantics with a new Exception...
NZKoz authored
118 end
84a14f2 Jeremy Kemper Raise ProtectedAttributeAssignmentError in development and test environm...
jeremy authored
119
dc4eec1 Pratik Merge docrails:
lifo authored
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 Michael Koziarski Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
122 class MissingAttributeError < NoMethodError
123 end
e48b062 Jeremy Kemper Sanitize Base#inspect. Closes #8392.
jeremy authored
124
4f68752 Jeremy Kemper Revert "Revert "Raise UnknownAttributeError when unknown attributes are ...
jeremy authored
125 # Raised when unknown attributes are supplied via mass assignment.
126 class UnknownAttributeError < NoMethodError
127 end
128
0432d15 Pratik Merge with docrails.
lifo authored
129 # Raised when an error occurred while doing a mass assignment to an attribute through the
dc4eec1 Pratik Merge docrails:
lifo authored
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 David Heinemeier Hansson Added MultiparameterAssignmentErrors and AttributeAssignmentError except...
dhh authored
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 Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
140
dc4eec1 Pratik Merge docrails:
lifo authored
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 David Heinemeier Hansson Added MultiparameterAssignmentErrors and AttributeAssignmentError except...
dhh authored
145 attr_reader :errors
146 def initialize(errors)
147 @errors = errors
148 end
149 end
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
150
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
151 # Active Record objects don't specify their attributes directly, but rather infer them from the table definition with
db045db David Heinemeier Hansson Initial
dhh authored
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 Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
154 # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
155 #
db045db David Heinemeier Hansson Initial
dhh authored
156 # See the mapping rules in table_name and the full example in link:files/README.html for more insight.
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
157 #
db045db David Heinemeier Hansson Initial
dhh authored
158 # == Creation
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
159 #
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
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 [BobSilv...
Marcel Molina authored
161 # you're receiving the data from somewhere else, like an HTTP request. It works like this:
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
162 #
0591c53 David Heinemeier Hansson Made the dynamic finders use the new find API and updated the examples h...
dhh authored
163 # user = User.new(:name => "David", :occupation => "Code Artist")
db045db David Heinemeier Hansson Initial
dhh authored
164 # user.name # => "David"
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
165 #
db045db David Heinemeier Hansson Initial
dhh authored
166 # You can also use block initialization:
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
167 #
db045db David Heinemeier Hansson Initial
dhh authored
168 # user = User.new do |u|
169 # u.name = "David"
170 # u.occupation = "Code Artist"
171 # end
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
172 #
db045db David Heinemeier Hansson Initial
dhh authored
173 # And of course you can just create a bare object and specify the attributes after the fact:
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
174 #
db045db David Heinemeier Hansson Initial
dhh authored
175 # user = User.new
176 # user.name = "David"
177 # user.occupation = "Code Artist"
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
178 #
db045db David Heinemeier Hansson Initial
dhh authored
179 # == Conditions
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
180 #
c5ec16e David Heinemeier Hansson Added simple hash conditions to find that'll just convert hash to an AND...
dhh authored
181 # Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement.
db045db David Heinemeier Hansson Initial
dhh authored
182 # The array form is to be used when the condition input is tainted and requires sanitization. The string form can
c5ec16e David Heinemeier Hansson Added simple hash conditions to find that'll just convert hash to an AND...
dhh authored
183 # be used for statements that don't involve tainted data. The hash form works much like the array form, except
2876707 Jeremy Kemper Pass a range in :conditions to use the SQL BETWEEN operator. Closes #697...
jeremy authored
184 # only equality and range is possible. Examples:
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
185 #
48052d7 Jeremy Kemper to_xml fixes, features, and speedup. Closes #4989.
jeremy authored
186 # class User < ActiveRecord::Base
db045db David Heinemeier Hansson Initial
dhh authored
187 # def self.authenticate_unsafely(user_name, password)
3dfa56c David Heinemeier Hansson Updated all references to the old find_first and find_all to use the new...
dhh authored
188 # find(:first, :conditions => "user_name = '#{user_name}' AND password = '#{password}'")
db045db David Heinemeier Hansson Initial
dhh authored
189 # end
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
190 #
db045db David Heinemeier Hansson Initial
dhh authored
191 # def self.authenticate_safely(user_name, password)
3dfa56c David Heinemeier Hansson Updated all references to the old find_first and find_all to use the new...
dhh authored
192 # find(:first, :conditions => [ "user_name = ? AND password = ?", user_name, password ])
db045db David Heinemeier Hansson Initial
dhh authored
193 # end
c5ec16e David Heinemeier Hansson Added simple hash conditions to find that'll just convert hash to an AND...
dhh authored
194 #
195 # def self.authenticate_safely_simply(user_name, password)
196 # find(:first, :conditions => { :user_name => user_name, :password => password })
197 # end
db045db David Heinemeier Hansson Initial
dhh authored
198 # end
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
199 #
2575b3b David Heinemeier Hansson Added extra words of caution for guarding against SQL-injection attacks
dhh authored
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 [BobSilv...
Marcel Molina authored
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 Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
202 # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+ before inserting them in the query,
c5ec16e David Heinemeier Hansson Added simple hash conditions to find that'll just convert hash to an AND...
dhh authored
203 # which will ensure that an attacker can't escape the query and fake the login (or worse).
2575b3b David Heinemeier Hansson Added extra words of caution for guarding against SQL-injection attacks
dhh authored
204 #
5cd38ca David Heinemeier Hansson Added documentation about named bind variables
dhh authored
205 # When using multiple parameters in the conditions, it can easily become hard to read exactly what the fourth or fifth
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
206 # question mark is supposed to represent. In those cases, you can resort to named bind variables instead. That's done by replacing
5cd38ca David Heinemeier Hansson Added documentation about named bind variables
dhh authored
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 var...
Marcel Molina authored
209 # Company.find(:first, :conditions => [
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
210 # "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
5cd38ca David Heinemeier Hansson Added documentation about named bind variables
dhh authored
211 # { :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' }
212 # ])
213 #
c5ec16e David Heinemeier Hansson Added simple hash conditions to find that'll just convert hash to an AND...
dhh authored
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 Kemper Pass a range in :conditions to use the SQL BETWEEN operator. Closes #697...
jeremy authored
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 David Heinemeier Hansson Added simple hash conditions to find that'll just convert hash to an AND...
dhh authored
223 #
aa4af60 Pratik Improve documentation.
lifo authored
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 David Heinemeier Hansson Initial
dhh authored
228 # == Overwriting default accessors
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
229 #
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobSilv...
Marcel Molina authored
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 Pratik Merge docrails.
lifo authored
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 David Heinemeier Hansson Initial
dhh authored
233 # Example:
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
234 #
db045db David Heinemeier Hansson Initial
dhh authored
235 # class Song < ActiveRecord::Base
236 # # Uses an integer of seconds to hold the length of the song
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
237 #
db045db David Heinemeier Hansson Initial
dhh authored
238 # def length=(minutes)
64092de Xavier Noria Improve documentation coverage and markup
fxn authored
239 # write_attribute(:length, minutes.to_i * 60)
db045db David Heinemeier Hansson Initial
dhh authored
240 # end
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
241 #
db045db David Heinemeier Hansson Initial
dhh authored
242 # def length
0591c53 David Heinemeier Hansson Made the dynamic finders use the new find API and updated the examples h...
dhh authored
243 # read_attribute(:length) / 60
db045db David Heinemeier Hansson Initial
dhh authored
244 # end
245 # end
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
246 #
98dc582 Pratik Merge docrails.
lifo authored
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 David Heinemeier Hansson Made the dynamic finders use the new find API and updated the examples h...
dhh authored
249 #
e4d845e Document automatically generated predicate methods for attributes. Close...
Marcel Molina authored
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 Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
254 #
e4d845e Document automatically generated predicate methods for attributes. Close...
Marcel Molina authored
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
264 # == Accessing attributes before they have been typecasted
4eab375 David Heinemeier Hansson Finished polishing API docs
dhh authored
265 #
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
266 # Sometimes you want to be able to read the raw attribute data without having the column-determined typecast run its course first.
dc4eec1 Pratik Merge docrails:
lifo authored
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 Pratik Merge docrails.
lifo authored
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 David Heinemeier Hansson Finished polishing API docs
dhh authored
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
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 David Heinemeier Hansson Finished polishing API docs
dhh authored
272 # want.
273 #
ac8fd7d David Heinemeier Hansson Added dynamic attribute-based finders as a cleaner way of getting object...
dhh authored
274 # == Dynamic attribute-based finders
275 #
a5a82d9 David Heinemeier Hansson Added extension capabilities to has_many and has_and_belongs_to_many pro...
dhh authored
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 David Heinemeier Hansson Missing doc updates
dhh authored
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 Pratik Merge docrails.
lifo authored
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 var...
Marcel Molina authored
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 Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
281 #
ac8fd7d David Heinemeier Hansson Added dynamic attribute-based finders as a cleaner way of getting object...
dhh authored
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 var...
Marcel Molina authored
284 # <tt>Person.find(:first, :conditions => ["user_name = ? AND password = ?", user_name, password])</tt>, you just do
ac8fd7d David Heinemeier Hansson Added dynamic attribute-based finders as a cleaner way of getting object...
dhh authored
285 # <tt>Person.find_by_user_name_and_password(user_name, password)</tt>.
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
286 #
98dc582 Pratik Merge docrails.
lifo authored
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 Xavier Noria Improve documentation coverage and markup
fxn authored
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 Emilio Tagua Added find_last_by dynamic finder [status:committed #762]
miloops authored
290 # Also you may call <tt>Payment.find_last_by_amount(amount, options)</tt> returning the last record matching that amount and options.
959f362 David Heinemeier Hansson Added find_all style to the new dynamic finders
dhh authored
291 #
a5a82d9 David Heinemeier Hansson Added extension capabilities to has_many and has_and_belongs_to_many pro...
dhh authored
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 Michael Koziarski Typo fix in documentation from [9090] References #11422
NZKoz authored
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 David Heinemeier Hansson Added extension capabilities to has_many and has_and_belongs_to_many pro...
dhh authored
294 #
295 # # No 'Summer' tag exists
296 # Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
297 #
a5a82d9 David Heinemeier Hansson Added extension capabilities to has_many and has_and_belongs_to_many pro...
dhh authored
298 # # Now the 'Summer' tag does exist
299 # Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
300 #
c10b225 David Heinemeier Hansson Fixed that ActiveRecord#Base.find_or_create/initialize would not honor a...
dhh authored
301 # # Now 'Bob' exist and is an 'admin'
302 # User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }
303 #
0432d15 Pratik Merge with docrails.
lifo authored
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 Sam Stephenson Added find_or_initialize_by_X which works like find_or_create_by_X but d...
sstephenson authored
305 #
306 # # No 'Winter' tag exists
307 # winter = Tag.find_or_initialize_by_name("Winter")
85fbb22 David Heinemeier Hansson Backed out of new_record? to new? transformation as it would screw up ex...
dhh authored
308 # winter.new_record? # true
d19e464 Sam Stephenson Added find_or_initialize_by_X which works like find_or_create_by_X but d...
sstephenson authored
309 #
14cc8d2 Jeremy Kemper find_or_create_by_* takes a hash so you can create with more attributes ...
jeremy authored
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 David Heinemeier Hansson Fixed documentation snafus #575, #576, #577, #585
dhh authored
317 # == Saving arrays, hashes, and other non-mappable objects in text columns
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
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
320 # This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work. Example:
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
321 #
db045db David Heinemeier Hansson Initial
dhh authored
322 # class User < ActiveRecord::Base
323 # serialize :preferences
324 # end
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
325 #
ca2eb16 Fix syntax error in documentation. Closes #4679. [mislav@nippur.irb.hr]
Marcel Molina authored
326 # user = User.create(:preferences => { "background" => "black", "display" => large })
db045db David Heinemeier Hansson Initial
dhh authored
327 # User.find(user.id).preferences # => { "background" => "black", "display" => large }
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
328 #
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
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
39e1ac6 Pratik Merge docrails
lifo authored
330 # descendant of a class not in the hierarchy. Example:
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
331 #
db045db David Heinemeier Hansson Initial
dhh authored
332 # class User < ActiveRecord::Base
66f44e6 David Heinemeier Hansson Updated documentation for serialize
dhh authored
333 # serialize :preferences, Hash
db045db David Heinemeier Hansson Initial
dhh authored
334 # end
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
335 #
0591c53 David Heinemeier Hansson Made the dynamic finders use the new find API and updated the examples h...
dhh authored
336 # user = User.create(:preferences => %w( one two three ))
db045db David Heinemeier Hansson Initial
dhh authored
337 # User.find(user.id).preferences # raises SerializationTypeMismatch
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
338 #
db045db David Heinemeier Hansson Initial
dhh authored
339 # == Single table inheritance
340 #
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobSilv...
Marcel Molina authored
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 David Heinemeier Hansson Initial
dhh authored
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 Pratik Merge docrails.
lifo authored
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 David Heinemeier Hansson Initial
dhh authored
351 #
f033833 David Heinemeier Hansson Improving documentation...
dhh authored
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 David Heinemeier Hansson Initial
dhh authored
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 Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
357 #
db045db David Heinemeier Hansson Initial
dhh authored
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 Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
361 # All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection.
98dc582 Pratik Merge docrails.
lifo authored
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 David Heinemeier Hansson Initial
dhh authored
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 Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
369 #
dc4eec1 Pratik Merge docrails:
lifo authored
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 David Heinemeier Hansson Initial
dhh authored
372 # <tt>:adapter</tt> key.
dc4eec1 Pratik Merge docrails:
lifo authored
373 # * AdapterNotFound - The <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a non-existent adapter
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
374 # (or a bad spelling of an existing one).
dc4eec1 Pratik Merge docrails:
lifo authored
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 David Heinemeier Hansson Added MultiparameterAssignmentErrors and AttributeAssignmentError except...
dhh authored
384 # objects that should be inspected to determine which attributes triggered the errors.
dc4eec1 Pratik Merge docrails:
lifo authored
385 # * AttributeAssignmentError - An error occurred while doing a mass assignment through the <tt>attributes=</tt> method.
d2fefbe David Heinemeier Hansson Added MultiparameterAssignmentErrors and AttributeAssignmentError except...
dhh authored
386 # You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error.
5707027 David Heinemeier Hansson Added better exception error when unknown column types are used with mig...
dhh authored
387 #
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
388 # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
dc4eec1 Pratik Merge docrails:
lifo authored
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 David Heinemeier Hansson Initial
dhh authored
390 # instances in the current object space.
391 class Base
dbbae5e Pratik Merge with docrails
lifo authored
392 ##
393 # :singleton-method:
db045db David Heinemeier Hansson Initial
dhh authored
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 risk danger olson Don't create instance writer methods for class attributes. Closes #7401...
technoweenie authored
396 cattr_accessor :logger, :instance_writer => false
e694114 Jeremy Kemper Deprecation: removed Reloadable.
jeremy authored
397
db045db David Heinemeier Hansson Initial
dhh authored
398 def self.inherited(child) #:nodoc:
399 @@subclasses[self] ||= []
400 @@subclasses[self] << child
401 super
402 end
e694114 Jeremy Kemper Deprecation: removed Reloadable.
jeremy authored
403
fed7d33 David Heinemeier Hansson Fixed documentation
dhh authored
404 def self.reset_subclasses #:nodoc:
bfbf6bb Jamis Buck Allow ARStore::Session to indicate that it should not be reloaded in dev...
jamis authored
405 nonreloadables = []
e7f61ea Jamis Buck squash the memleak in dev mode finally (fingers crossed, here)
jamis authored
406 subclasses.each do |klass|
c08547d Joshua Peek Namespace Inflector, Dependencies, OrderedOptions, and TimeZone under Ac...
josh authored
407 unless ActiveSupport::Dependencies.autoloaded? klass
bfbf6bb Jamis Buck Allow ARStore::Session to indicate that it should not be reloaded in dev...
jamis authored
408 nonreloadables << klass
409 next
410 end
e7f61ea Jamis Buck squash the memleak in dev mode finally (fingers crossed, here)
jamis authored
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 Buck Allow ARStore::Session to indicate that it should not be reloaded in dev...
jamis authored
414 @@subclasses = {}
415 nonreloadables.each { |klass| (@@subclasses[klass.superclass] ||= []) << klass }
3c0129a David Heinemeier Hansson Fixed memory leak with Active Record classes when Dependencies.mechanism...
dhh authored
416 end
417
db045db David Heinemeier Hansson Initial
dhh authored
418 @@subclasses = {}
dbbae5e Pratik Merge with docrails
lifo authored
419
420 ##
421 # :singleton-method:
a293278 Pratik Merge docrails
lifo authored
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 risk danger olson Don't create instance writer methods for class attributes. Closes #7401...
technoweenie authored
447 cattr_accessor :configurations, :instance_writer => false
c4a3634 Jeremy Kemper Corrected @@configurations typo. #1410 [david@ruppconsulting.com]
jeremy authored
448 @@configurations = {}
449
dbbae5e Pratik Merge with docrails
lifo authored
450 ##
451 # :singleton-method:
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
452 # Accessor for the prefix type that will be prepended to every primary key column name. The options are :table_name and
db045db David Heinemeier Hansson Initial
dhh authored
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 Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
455 # that this is a global setting for all Active Records.
1a11bff risk danger olson Don't create instance writer methods for class attributes. Closes #7401...
technoweenie authored
456 cattr_accessor :primary_key_prefix_type, :instance_writer => false
db045db David Heinemeier Hansson Initial
dhh authored
457 @@primary_key_prefix_type = nil
458
dbbae5e Pratik Merge with docrails
lifo authored
459 ##
460 # :singleton-method:
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
461 # Accessor for the name of the prefix string to prepend to every table name. So if set to "basecamp_", all
098fa94 David Heinemeier Hansson Fixed documentation snafus #575, #576, #577, #585
dhh authored
462 # table names will be named like "basecamp_projects", "basecamp_people", etc. This is a convenient way of creating a namespace
db045db David Heinemeier Hansson Initial
dhh authored
463 # for tables in a shared database. By default, the prefix is the empty string.
1a11bff risk danger olson Don't create instance writer methods for class attributes. Closes #7401...
technoweenie authored
464 cattr_accessor :table_name_prefix, :instance_writer => false
db045db David Heinemeier Hansson Initial
dhh authored
465 @@table_name_prefix = ""
466
dbbae5e Pratik Merge with docrails
lifo authored
467 ##
468 # :singleton-method:
db045db David Heinemeier Hansson Initial
dhh authored
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 risk danger olson Don't create instance writer methods for class attributes. Closes #7401...
technoweenie authored
471 cattr_accessor :table_name_suffix, :instance_writer => false
db045db David Heinemeier Hansson Initial
dhh authored
472 @@table_name_suffix = ""
473
dbbae5e Pratik Merge with docrails
lifo authored
474 ##
475 # :singleton-method:
84a14f2 Jeremy Kemper Raise ProtectedAttributeAssignmentError in development and test environm...
jeremy authored
476 # Indicates whether table names should be the pluralized versions of the corresponding class names.
98dc582 Pratik Merge docrails.
lifo authored
477 # If true, the default table name for a Product class will be +products+. If false, it would just be +product+.
db045db David Heinemeier Hansson Initial
dhh authored
478 # See table_name for the full rules on table/class naming. This is true, by default.
1a11bff risk danger olson Don't create instance writer methods for class attributes. Closes #7401...
technoweenie authored
479 cattr_accessor :pluralize_table_names, :instance_writer => false
db045db David Heinemeier Hansson Initial
dhh authored
480 @@pluralize_table_names = true
481
dbbae5e Pratik Merge with docrails
lifo authored
482 ##
483 # :singleton-method:
84a14f2 Jeremy Kemper Raise ProtectedAttributeAssignmentError in development and test environm...
jeremy authored
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
485 # make it much easier to overview things during debugging (when used through a reader like +tail+ and on a black background), but
911614d David Heinemeier Hansson Added ActiveRecord::Base.colorize_logging to control whether to use colo...
dhh authored
486 # may complicate matters if you use software like syslog. This is true, by default.
1a11bff risk danger olson Don't create instance writer methods for class attributes. Closes #7401...
technoweenie authored
487 cattr_accessor :colorize_logging, :instance_writer => false
911614d David Heinemeier Hansson Added ActiveRecord::Base.colorize_logging to control whether to use colo...
dhh authored
488 @@colorize_logging = true
489
dbbae5e Pratik Merge with docrails
lifo authored
490 ##
491 # :singleton-method:
60de8c1 David Heinemeier Hansson Added Base.default_timezone accessor that determines whether to use Time...
dhh authored
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 risk danger olson Don't create instance writer methods for class attributes. Closes #7401...
technoweenie authored
494 cattr_accessor :default_timezone, :instance_writer => false
60de8c1 David Heinemeier Hansson Added Base.default_timezone accessor that determines whether to use Time...
dhh authored
495 @@default_timezone = :local
d8641ca Jeremy Kemper CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. Mos...
jeremy authored
496
dbbae5e Pratik Merge with docrails
lifo authored
497 ##
498 # :singleton-method:
24c3599 Sam Stephenson Support using different database adapters for development and test with ...
sstephenson authored
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 Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
501 # specific) SQL statements. If :ruby, the schema is dumped as an
24c3599 Sam Stephenson Support using different database adapters for development and test with ...
sstephenson authored
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 risk danger olson Don't create instance writer methods for class attributes. Closes #7401...
technoweenie authored
505 cattr_accessor :schema_format , :instance_writer => false
660952e David Heinemeier Hansson CHANGED DEFAULT: ActiveRecord::Base.schema_format is now :ruby by defaul...
dhh authored
506 @@schema_format = :ruby
3b0e1d9 Joshua Peek Prefer string core_ext inflector methods over directly accessing Inflect...
josh authored
507
dbbae5e Pratik Merge with docrails
lifo authored
508 ##
509 # :singleton-method:
bbab639 Nik Wakelin Set config.active_record.timestamped_migrations = false to have migratio...
nikz authored
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 Rodrigo Kochenburger Add ActiveRecord option to store the full class name on STI's type colum...
divoxx authored
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 Joshua Peek Prefer string core_ext inflector methods over directly accessing Inflect...
josh authored
517
2530d0e Pratik Added default_scope to Base [#1381 state:committed] (Paweł Kondzior)
lifo authored
518 # Stores the default scope for the class
519 class_inheritable_accessor :default_scoping, :instance_writer => false
520 self.default_scoping = []
521
db045db David Heinemeier Hansson Initial
dhh authored
522 class << self # Class methods
d5a4d5a David Heinemeier Hansson Added ActiveRecord::Base.find(:last) (closes #11338) [miloops]
dhh authored
523 # Find operates with four different retrieval approaches:
7669011 David Heinemeier Hansson Fixes for postgresql testing #1129, #1130, #1131
dhh authored
524 #
98dc582 Pratik Merge docrails.
lifo authored
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 David Heinemeier Hansson Fixes for postgresql testing #1129, #1130, #1131
dhh authored
526 # If no record can be found for all of the listed ids, then RecordNotFound will be raised.
98dc582 Pratik Merge docrails.
lifo authored
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 Pratik Merge docrails
lifo authored
539 # ==== Parameters
98dc582 Pratik Merge docrails.
lifo authored
540 #
9cb5400 Pratik Merge docrails
lifo authored
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 Pratik Merge docrails.
lifo authored
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 Emilio Tagua Add :having option to find, to use in combination with grouped finds. Al...
miloops authored
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 Pratik Merge docrails.
lifo authored
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.
39e1ac6 Pratik Merge docrails
lifo authored
547 # * <tt>:joins</tt> - Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed),
548 # 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),
549 # or an array containing a mixture of both strings and named associations.
9661395 Remove references to nonexistent :joins documentation. Closes #10498 [tp...
Marcel Molina authored
550 # 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 Xavier Noria Improve documentation coverage and markup
fxn authored
551 # Pass <tt>:readonly => false</tt> to override.
98dc582 Pratik Merge docrails.
lifo authored
552 # * <tt>:include</tt> - Names associations that should be loaded alongside. The symbols named refer
515886a David Heinemeier Hansson Added documentation for new Base.find API and eager association loading
dhh authored
553 # to already defined associations. See eager loading under Associations.
98dc582 Pratik Merge docrails.
lifo authored
554 # * <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 Pratik Merge docrails
lifo authored
555 # include the joined columns. Takes a string with the SELECT SQL fragment (e.g. "id, name").
98dc582 Pratik Merge docrails.
lifo authored
556 # * <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 Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
557 # of a database view).
98dc582 Pratik Merge docrails.
lifo authored
558 # * <tt>:readonly</tt> - Mark the returned records read-only so they cannot be saved or updated.
559 # * <tt>:lock</tt> - An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE".
64092de Xavier Noria Improve documentation coverage and markup
fxn authored
560 # <tt>:lock => true</tt> gives connection's default exclusive lock, usually "FOR UPDATE".
7669011 David Heinemeier Hansson Fixes for postgresql testing #1129, #1130, #1131
dhh authored
561 #
98dc582 Pratik Merge docrails.
lifo authored
562 # ==== Examples
563 #
564 # # find by id
db045db David Heinemeier Hansson Initial
dhh authored
565 # Person.find(1) # returns the object for ID = 1
566 # Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
567 # Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobSilv...
Marcel Molina authored
568 # Person.find([1]) # returns an array for the object with ID = 1
515886a David Heinemeier Hansson Added documentation for new Base.find API and eager association loading
dhh authored
569 # Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
570 #
1e9e198 Jeremy Kemper Note that find results may not be in the same order as the id arguments....
jeremy authored
571 # Note that returned records may not be in the same order as the ids you
64092de Xavier Noria Improve documentation coverage and markup
fxn authored
572 # provide since database rows are unordered. Give an explicit <tt>:order</tt>
1e9e198 Jeremy Kemper Note that find results may not be in the same order as the id arguments....
jeremy authored
573 # to ensure the results are sorted.
574 #
98dc582 Pratik Merge docrails.
lifo authored
575 # ==== Examples
576 #
577 # # find first
7d01005 David Heinemeier Hansson Fixed documentation and prepared for release of 0.12
dhh authored
578 # Person.find(:first) # returns the first object fetched by SELECT * FROM people
515886a David Heinemeier Hansson Added documentation for new Base.find API and eager association loading
dhh authored
579 # Person.find(:first, :conditions => [ "user_name = ?", user_name])
9cb5400 Pratik Merge docrails
lifo authored
580 # Person.find(:first, :conditions => [ "user_name = :u", { :u => user_name }])
515886a David Heinemeier Hansson Added documentation for new Base.find API and eager association loading
dhh authored
581 # Person.find(:first, :order => "created_on DESC", :offset => 5)
582 #
98dc582 Pratik Merge docrails.
lifo authored
583 # # find last
d5a4d5a David Heinemeier Hansson Added ActiveRecord::Base.find(:last) (closes #11338) [miloops]
dhh authored
584 # Person.find(:last) # returns the last object fetched by SELECT * FROM people
585 # Person.find(:last, :conditions => [ "user_name = ?", user_name])
586 # Person.find(:last, :order => "created_on DESC", :offset => 5)
587 #
98dc582 Pratik Merge docrails.
lifo authored
588 # # find all
7d01005 David Heinemeier Hansson Fixed documentation and prepared for release of 0.12
dhh authored
589 # Person.find(:all) # returns an array of objects for all the rows fetched by SELECT * FROM people
515886a David Heinemeier Hansson Added documentation for new Base.find API and eager association loading
dhh authored
590 # Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50)
aa4af60 Pratik Improve documentation.
lifo authored
591 # Person.find(:all, :conditions => { :friends => ["Bob", "Steve", "Fred"] }
515886a David Heinemeier Hansson Added documentation for new Base.find API and eager association loading
dhh authored
592 # Person.find(:all, :offset => 10, :limit => 10)
593 # Person.find(:all, :include => [ :account, :friends ])
3309268 Jeremy Kemper Add :group option, correspond to GROUP BY, to the find method and to the...
jeremy authored
594 # Person.find(:all, :group => "category")
15aa6e0 Jeremy Kemper r4644@asus: jeremy | 2006-06-16 14:57:03 -0700
jeremy authored
595 #
98dc582 Pratik Merge docrails.
lifo authored
596 # Example for find with a lock: Imagine two concurrent transactions:
597 # each will read <tt>person.visits == 2</tt>, add 1 to it, and save, resulting
598 # in two saves of <tt>person.visits = 3</tt>. By locking the row, the second
15aa6e0 Jeremy Kemper r4644@asus: jeremy | 2006-06-16 14:57:03 -0700
jeremy authored
599 # transaction has to wait until the first is finished; we get the
98dc582 Pratik Merge docrails.
lifo authored
600 # expected <tt>person.visits == 4</tt>.
601 #
15aa6e0 Jeremy Kemper r4644@asus: jeremy | 2006-06-16 14:57:03 -0700
jeremy authored
602 # Person.transaction do
603 # person = Person.find(1, :lock => true)
604 # person.visits += 1
605 # person.save!
606 # end
6bd672e David Heinemeier Hansson Added that Base#find takes an optional options hash, including :conditio...
dhh authored
607 def find(*args)
edd68a5 David Heinemeier Hansson Refactored in use of extract_options! (closes #9079) [josh]
dhh authored
608 options = args.extract_options!
c9c1852 David Heinemeier Hansson Making ActiveRecord faster [skaes]
dhh authored
609 validate_find_options(options)
610 set_readonly_option!(options)
64fcb75 Jeremy Kemper r3618@sedna: jeremy | 2005-10-14 12:06:03 -0700
jeremy authored
611
abc895b David Heinemeier Hansson Added new Base.find API and deprecated find_all, find_first. Added preli...
dhh authored
612 case args.first
c9c1852 David Heinemeier Hansson Making ActiveRecord faster [skaes]
dhh authored
613 when :first then find_initial(options)
d5a4d5a David Heinemeier Hansson Added ActiveRecord::Base.find(:last) (closes #11338) [miloops]
dhh authored
614 when :last then find_last(options)
c9c1852 David Heinemeier Hansson Making ActiveRecord faster [skaes]
dhh authored
615 when :all then find_every(options)
616 else find_from_ids(args, options)
db045db David Heinemeier Hansson Initial
dhh authored
617 end
618 end
3b0e1d9 Joshua Peek Prefer string core_ext inflector methods over directly accessing Inflect...
josh authored
619
98dc582 Pratik Merge docrails.
lifo authored
620 # A convenience wrapper for <tt>find(:first, *args)</tt>. You can pass in all the
621 # same arguments to this method as you can to <tt>find(:first)</tt>.
c6f2af5 David Heinemeier Hansson Added ActiveRecord#Base.all/first/last as aliases for find(:all/:first/:...
dhh authored
622 def first(*args)
623 find(:first, *args)
624 end
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
625
98dc582 Pratik Merge docrails.
lifo authored
626 # A convenience wrapper for <tt>find(:last, *args)</tt>. You can pass in all the
627 # same arguments to this method as you can to <tt>find(:last)</tt>.
c6f2af5 David Heinemeier Hansson Added ActiveRecord#Base.all/first/last as aliases for find(:all/:first/:...
dhh authored
628 def last(*args)
629 find(:last, *args)
630 end
3b0e1d9 Joshua Peek Prefer string core_ext inflector methods over directly accessing Inflect...
josh authored
631
0a6980f Let Base.all use conditions etc like first/last
David Heinemeier Hansson authored
632 # This is an alias for find(:all). You can pass in all the same arguments to this method as you can
633 # to find(:all)
634 def all(*args)
635 find(:all, *args)
636 end
3b0e1d9 Joshua Peek Prefer string core_ext inflector methods over directly accessing Inflect...
josh authored
637
98dc582 Pratik Merge docrails.
lifo authored
638 # Executes a custom SQL query against your database and returns all the results. The results will
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
639 # be returned as an array with columns requested encapsulated as attributes of the model you call
a293278 Pratik Merge docrails
lifo authored
640 # this method from. If you call <tt>Product.find_by_sql</tt> then the results will be returned in
641 # 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
642 #
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
643 # If you call a complicated SQL query which spans multiple tables the columns specified by the
644 # 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
645 # table.
646 #
98dc582 Pratik Merge docrails.
lifo authored
647 # The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
648 # no database agnostic conversions performed. This should be a last resort because using, for example,
649 # MySQL specific terms will lock you to using that particular database engine or require you to
a293278 Pratik Merge docrails
lifo authored
650 # change your call if you switch engines.
edf32ce More complete documentation for find_by_sql. Closes #7912 [fearoffish]
Marcel Molina authored
651 #
652 # ==== Examples
98dc582 Pratik Merge docrails.
lifo authored
653 # # A simple SQL query spanning multiple tables
edf32ce More complete documentation for find_by_sql. Closes #7912 [fearoffish]
Marcel Molina authored
654 # Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
655 # > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
656 #
657 # # You can use the same string replacement techniques as you can with ActiveRecord#find
658 # Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
659 # > [#<Post:0x36bff9c @attributes={"first_name"=>"The Cheap Man Buys Twice"}>, ...]
db045db David Heinemeier Hansson Initial
dhh authored
660 def find_by_sql(sql)
6e3d2a7 Jeremy Kemper Revert "Performance: freeze cached rows instead of duping"
jeremy authored
661 connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) }
db045db David Heinemeier Hansson Initial
dhh authored
662 end
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
663
dbbae5e Pratik Merge with docrails
lifo authored
664
665 # Returns true if a record exists in the table that matches the +id+ or
666 # conditions given, or false otherwise. The argument can take four forms:
667 #
668 # * Integer - Finds the record with this primary key.
669 # * String - Finds the record with a primary key corresponding to this
670 # string (such as <tt>'5'</tt>).
671 # * Array - Finds the record that matches these +find+-style conditions
672 # (such as <tt>['color = ?', 'red']</tt>).
673 # * Hash - Finds the record that matches these +find+-style conditions
674 # (such as <tt>{:color => 'red'}</tt>).
971ed15 Document API for exists?'s parameter and provide examples of usage. Clos...
Marcel Molina authored
675 #
dbbae5e Pratik Merge with docrails
lifo authored
676 # For more information about specifying conditions as a Hash or Array,
677 # see the Conditions section in the introduction to ActiveRecord::Base.
971ed15 Document API for exists?'s parameter and provide examples of usage. Clos...
Marcel Molina authored
678 #
dbbae5e Pratik Merge with docrails
lifo authored
679 # Note: You can't pass in a condition as a string (like <tt>name =
680 # 'Jamie'</tt>), since it would be sanitized and then queried against
681 # the primary key column, like <tt>id = 'name = \'Jamie\''</tt>.
971ed15 Document API for exists?'s parameter and provide examples of usage. Clos...
Marcel Molina authored
682 #
683 # ==== Examples
abc895b David Heinemeier Hansson Added new Base.find API and deprecated find_all, find_first. Added preli...
dhh authored
684 # Person.exists?(5)
58ebf30 Jeremy Kemper The exists? class method should treat a string argument as an id rather ...
jeremy authored
685 # Person.exists?('5')
8085cbf David Heinemeier Hansson Added support for conditions on Base.exists? (closes #5689) [josh@joshpe...
dhh authored
686 # Person.exists?(:name => "David")
58ebf30 Jeremy Kemper The exists? class method should treat a string argument as an id rather ...
jeremy authored
687 # Person.exists?(['name LIKE ?', "%#{query}%"])
688 def exists?(id_or_conditions)
0ad24df risk danger olson Optimize ActiveRecord::Base#exists? to use #select_all instead of #find....
technoweenie authored
689 connection.select_all(
690 construct_finder_sql(
3b0e1d9 Joshua Peek Prefer string core_ext inflector methods over directly accessing Inflect...
josh authored
691 :select => "#{quoted_table_name}.#{primary_key}",
692 :conditions => expand_id_conditions(id_or_conditions),
0ad24df risk danger olson Optimize ActiveRecord::Base#exists? to use #select_all instead of #find....
technoweenie authored
693 :limit => 1
3b0e1d9 Joshua Peek Prefer string core_ext inflector methods over directly accessing Inflect...
josh authored
694 ),
0ad24df risk danger olson Optimize ActiveRecord::Base#exists? to use #select_all instead of #find....
technoweenie authored
695 "#{name} Exists"
696 ).size > 0
db045db David Heinemeier Hansson Initial
dhh authored
697 end
abc895b David Heinemeier Hansson Added new Base.find API and deprecated find_all, find_first. Added preli...
dhh authored
698
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
699 # Creates an object (or multiple objects) and saves it to the database, if validations pass.
a23bea7 Document API for create's attributes parameter and provide examples. Clo...
Marcel Molina authored
700 # The resulting object is returned whether the object was saved successfully to the database or not.
701 #
702 # The +attributes+ parameter can be either be a Hash or an Array of Hashes. These Hashes describe the
703 # attributes on the objects that are to be created.
704 #
705 # ==== Examples
706 # # Create a single new object
707 # User.create(:first_name => 'Jamie')
dd120ed David Heinemeier Hansson Added block-setting of attributes for Base.create like Base.new already ...
dhh authored
708 #
a23bea7 Document API for create's attributes parameter and provide examples. Clo...
Marcel Molina authored
709 # # Create an Array of new objects
dc4eec1 Pratik Merge docrails:
lifo authored
710 # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])
dd120ed David Heinemeier Hansson Added block-setting of attributes for Base.create like Base.new already ...
dhh authored
711 #
712 # # Create a single object and pass it into a block to set other attributes.
713 # User.create(:first_name => 'Jamie') do |u|
714 # u.is_admin = false
715 # end
716 #
717 # # Creating an Array of new objects using a block, where the block is executed for each object:
dc4eec1 Pratik Merge docrails:
lifo authored
718 # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u|
dd120ed David Heinemeier Hansson Added block-setting of attributes for Base.create like Base.new already ...
dhh authored
719 # u.is_admin = false
3b0e1d9 Joshua Peek Prefer string core_ext inflector methods over directly accessing Inflect...
josh authored
720 # end
dd120ed David Heinemeier Hansson Added block-setting of attributes for Base.create like Base.new already ...
dhh authored
721 def create(attributes = nil, &block)
efa81da David Heinemeier Hansson Added the option of supplying an array of ids and attributes to Base#upd...
dhh authored
722 if attributes.is_a?(Array)
dd120ed David Heinemeier Hansson Added block-setting of attributes for Base.create like Base.new already ...
dhh authored
723 attributes.collect { |attr| create(attr, &block) }
efa81da David Heinemeier Hansson Added the option of supplying an array of ids and attributes to Base#upd...
dhh authored
724 else
725 object = new(attributes)
dd120ed David Heinemeier Hansson Added block-setting of attributes for Base.create like Base.new already ...
dhh authored
726 yield(object) if block_given?
efa81da David Heinemeier Hansson Added the option of supplying an array of ids and attributes to Base#upd...
dhh authored
727 object.save
728 object
729 end
db045db David Heinemeier Hansson Initial
dhh authored
730 end
731
1b7a18d Document options and add examples for update. Closes #7985 [fearoffish]
Marcel Molina authored
732 # Updates an object (or multiple objects) and saves it to the database, if validations pass.
733 # The resulting object is returned whether the object was saved successfully to the database or not.
5e99422 David Heinemeier Hansson Updated docs (closes #3799) [ruby@bobsilva.com]
dhh authored
734 #
a293278 Pratik Merge docrails
lifo authored
735 # ==== Parameters
5e99422 David Heinemeier Hansson Updated docs (closes #3799) [ruby@bobsilva.com]
dhh authored
736 #
dc4eec1 Pratik Merge docrails:
lifo authored
737 # * +id+ - This should be the id or an array of ids to be updated.
738 # * +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
739 #
740 # ==== Examples
741 #
742 # # Updating one record:
dc4eec1 Pratik Merge docrails:
lifo authored
743 # Person.update(15, { :user_name => 'Samuel', :group => 'expert' })
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
744 #
1b7a18d Document options and add examples for update. Closes #7985 [fearoffish]
Marcel Molina authored
745 # # Updating multiple records:
dc4eec1 Pratik Merge docrails:
lifo authored
746 # people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
5e99422 David Heinemeier Hansson Updated docs (closes #3799) [ruby@bobsilva.com]
dhh authored
747 # Person.update(people.keys, people.values)
db045db David Heinemeier Hansson Initial
dhh authored
748 def update(id, attributes)
efa81da David Heinemeier Hansson Added the option of supplying an array of ids and attributes to Base#upd...
dhh authored
749 if id.is_a?(Array)
750 idx = -1
8b5f4e4 Jeremy Kemper Ruby 1.9 compat: fix warnings, shadowed block vars, and unitialized inst...
jeremy authored
751 id.collect { |one_id| idx += 1; update(one_id, attributes[idx]) }
efa81da David Heinemeier Hansson Added the option of supplying an array of ids and attributes to Base#upd...
dhh authored
752 else
753 object = find(id)
754 object.update_attributes(attributes)
755 object
756 end
db045db David Heinemeier Hansson Initial
dhh authored
757 end
758
39e1ac6 Pratik Merge docrails
lifo authored
759 # Deletes the row with a primary key matching the +id+ argument, using a
760 # SQL +DELETE+ statement, and returns the number of rows deleted. Active
761 # Record objects are not instantiated, so the object's callbacks are not
762 # executed, including any <tt>:dependent</tt> association options or
763 # Observer methods.
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
764 #
39e1ac6 Pratik Merge docrails
lifo authored
765 # 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
766 #
39e1ac6 Pratik Merge docrails
lifo authored
767 # Note: Although it is often much faster than the alternative,
768 # <tt>#destroy</tt>, skipping callbacks might bypass business logic in
769 # your application that ensures referential integrity or performs other
770 # essential jobs.
6a45e01 Document options and add examples for delete. Closes #7986 [fearoffish]
Marcel Molina authored
771 #
772 # ==== Examples
773 #
39e1ac6 Pratik Merge docrails
lifo authored
774 # # Delete a single row
6a45e01 Document options and add examples for delete. Closes #7986 [fearoffish]
Marcel Molina authored
775 # Todo.delete(1)
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
776 #
39e1ac6 Pratik Merge docrails
lifo authored
777 # # Delete multiple rows
778 # Todo.delete([2,3,4])
648b8fd David Heinemeier Hansson Added Base.destroy and Base.delete to remove records without holding a r...
dhh authored
779 def delete(id)
98165fd Jeremy Kemper Consistently quote primary key column names. Closes #7763.
jeremy authored
780 delete_all([ "#{connection.quote_column_name(primary_key)} IN (?)", id ])
648b8fd David Heinemeier Hansson Added Base.destroy and Base.delete to remove records without holding a r...
dhh authored
781 end
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
782
ed69b38 Document options and add examples for destroy. Closes #7988 [fearoffish]
Marcel Molina authored
783 # Destroy an object (or multiple objects) that has the given id, the object is instantiated first,
784 # therefore all callbacks and filters are fired off before the object is deleted. This method is
785 # less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
786 #
787 # 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
788 # from the attributes, and then calls destroy on it.
789 #
a293278 Pratik Merge docrails
lifo authored
790 # ==== Parameters
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
791 #
dc4eec1 Pratik Merge docrails:
lifo authored
792 # * +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
793 #
794 # ==== Examples
795 #
796 # # Destroy a single object
797 # Todo.destroy(1)
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
798 #
ed69b38 Document options and add examples for destroy. Closes #7988 [fearoffish]
Marcel Molina authored
799 # # Destroy multiple objects
800 # todos = [1,2,3]
801 # Todo.destroy(todos)
648b8fd David Heinemeier Hansson Added Base.destroy and Base.delete to remove records without holding a r...
dhh authored
802 def destroy(id)
8b5f4e4 Jeremy Kemper Ruby 1.9 compat: fix warnings, shadowed block vars, and unitialized inst...
jeremy authored
803 if id.is_a?(Array)
804 id.map { |one_id| destroy(one_id) }
805 else
806 find(id).destroy
807 end
648b8fd David Heinemeier Hansson Added Base.destroy and Base.delete to remove records without holding a r...
dhh authored
808 end
809
4f1d353 Document options and add examples for update_all. Closes #7990 [fearoffi...
Marcel Molina authored
810 # Updates all records with details given if they match a set of conditions supplied, limits and order can
6ef3546 Pratik Merge docrails
lifo authored
811 # also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the
812 # database. It does not instantiate the involved models and it does not trigger Active Record callbacks.
a38f28f Jeremy Kemper Base.update_all :order and :limit options. Useful for MySQL updates that...
jeremy authored
813 #
a293278 Pratik Merge docrails
lifo authored
814 # ==== Parameters
4f1d353 Document options and add examples for update_all. Closes #7990 [fearoffi...
Marcel Molina authored
815 #
c3f53f4 Pratik Merge docrails
lifo authored
816 # * +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 Pratik Merge with docrails.
lifo authored
817 # * +conditions+ - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro for more info.
6ef3546 Pratik Merge docrails
lifo authored
818 # * +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 [fearoffi...
Marcel Molina authored
819 #
820 # ==== Examples
821 #
822 # # Update all billing objects with the 3 different attributes given
823 # Billing.update_all( "category = 'authorized', approved = 1, author = 'David'" )
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
824 #
4f1d353 Document options and add examples for update_all. Closes #7990 [fearoffi...
Marcel Molina authored
825 # # Update records that match our conditions
826 # Billing.update_all( "author = 'David'", "title LIKE '%Rails%'" )
827 #
828 # # Update records that match our conditions but limit it to 5 ordered by date
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
829 # Billing.update_all( "author = 'David'", "title LIKE '%Rails%'",
4f1d353 Document options and add examples for update_all. Closes #7990 [fearoffi...
Marcel Molina authored
830 # :order => 'created_at', :limit => 5 )
a38f28f Jeremy Kemper Base.update_all :order and :limit options. Useful for MySQL updates that...
jeremy authored
831 def update_all(updates, conditions = nil, options = {})
ebe3a0d Jeremy Kemper More thoroughly quote table names. Exposes some issues with sqlite2 adap...
jeremy authored
832 sql = "UPDATE #{quoted_table_name} SET #{sanitize_sql_for_assignment(updates)} "
7c9851d Tarmo Tänav Support :limit on update_all so that has_many with :limit can be safely ...
tarmo authored
833
a38f28f Jeremy Kemper Base.update_all :order and :limit options. Useful for MySQL updates that...
jeremy authored
834 scope = scope(:find)
7c9851d Tarmo Tänav Support :limit on update_all so that has_many with :limit can be safely ...
tarmo authored
835
836 select_sql = ""
837 add_conditions!(select_sql, conditions, scope)
838
839 if options.has_key?(:limit) || (scope && scope[:limit])
840 # Only take order from scope if limit is also provided by scope, this
841 # is useful for updating a has_many association with a limit.
842 add_order!(select_sql, options[:order], scope)
843
844 add_limit!(select_sql, options, scope)
845 sql.concat(connection.limited_update_conditions(select_sql, quoted_table_name, connection.quote_column_name(primary_key)))
846 else
847 add_order!(select_sql, options[:order], nil)
848 sql.concat(select_sql)
849 end
850
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
851 connection.update(sql, "#{name} Update")
db045db David Heinemeier Hansson Initial
dhh authored
852 end
0d2db8a David Heinemeier Hansson Added Base.update_collection that can update an array of id/attribute pa...
dhh authored
853
39e1ac6 Pratik Merge docrails
lifo authored
854 # Destroys the records matching +conditions+ by instantiating each
855 # record and calling its +destroy+ method. Each object's callbacks are
856 # executed (including <tt>:dependent</tt> association options and
857 # +before_destroy+/+after_destroy+ Observer methods). Returns the
858 # collection of objects that were destroyed; each will be frozen, to
859 # reflect that no changes should be made (since they can't be
860 # persisted).
861 #
862 # Note: Instantiation, callback execution, and deletion of each
863 # record can be time consuming when you're removing many records at
864 # once. It generates at least one SQL +DELETE+ query per record (or
865 # possibly more, to enforce your callbacks). If you want to delete many
866 # rows quickly, without concern for their associations or callbacks, use
867 # +delete_all+ instead.
4b055a4 Jeremy Kemper Update destroy_all and delete_all documentation to better describe their...
jeremy authored
868 #
a293278 Pratik Merge docrails
lifo authored
869 # ==== Parameters
4b055a4 Jeremy Kemper Update destroy_all and delete_all documentation to better describe their...
jeremy authored
870 #
39e1ac6 Pratik Merge docrails
lifo authored
871 # * +conditions+ - A string, array, or hash that specifies which records
872 # to destroy. If omitted, all records are destroyed. See the
873 # Conditions section in the introduction to ActiveRecord::Base for
874 # more information.
4b055a4 Jeremy Kemper Update destroy_all and delete_all documentation to better describe their...
jeremy authored
875 #
39e1ac6 Pratik Merge docrails
lifo authored
876 # ==== Examples
4b055a4 Jeremy Kemper Update destroy_all and delete_all documentation to better describe their...
jeremy authored
877 #
a293278 Pratik Merge docrails
lifo authored
878 # Person.destroy_all("last_login < '2004-04-04'")
39e1ac6 Pratik Merge docrails
lifo authored
879 # Person.destroy_all(:status => "inactive")
db045db David Heinemeier Hansson Initial
dhh authored
880 def destroy_all(conditions = nil)
3dfa56c David Heinemeier Hansson Updated all references to the old find_first and find_all to use the new...
dhh authored
881 find(:all, :conditions => conditions).each { |object| object.destroy }
db045db David Heinemeier Hansson Initial
dhh authored
882 end
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
883
4b055a4 Jeremy Kemper Update destroy_all and delete_all documentation to better describe their...
jeremy authored
884 # Deletes the records matching +conditions+ without instantiating the records first, and hence not
6ef3546 Pratik Merge docrails
lifo authored
885 # calling the +destroy+ method nor invoking callbacks. This is a single SQL DELETE statement that
a293278 Pratik Merge docrails
lifo authored
886 # goes straight to the database, much more efficient than +destroy_all+. Be careful with relations
887 # though, in particular <tt>:dependent</tt> rules defined on associations are not honored.
4b055a4 Jeremy Kemper Update destroy_all and delete_all documentation to better describe their...
jeremy authored
888 #
a293278 Pratik Merge docrails
lifo authored
889 # ==== Parameters
4b055a4 Jeremy Kemper Update destroy_all and delete_all documentation to better describe their...
jeremy authored
890 #
dc4eec1 Pratik Merge docrails:
lifo authored
891 # * +conditions+ - Conditions are specified the same way as with +find+ method.
4b055a4 Jeremy Kemper Update destroy_all and delete_all documentation to better describe their...
jeremy authored
892 #
893 # ==== Example
894 #
a293278 Pratik Merge docrails
lifo authored
895 # Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
896 # Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
4b055a4 Jeremy Kemper Update destroy_all and delete_all documentation to better describe their...
jeremy authored
897 #
a293278 Pratik Merge docrails
lifo authored
898 # Both calls delete the affected posts all at once with a single DELETE statement. If you need to destroy dependent
6ef3546 Pratik Merge docrails
lifo authored
899 # associations or call your <tt>before_*</tt> or +after_destroy+ callbacks, use the +destroy_all+ method instead.
db045db David Heinemeier Hansson Initial
dhh authored
900 def delete_all(conditions = nil)
9b6207c Jeremy Kemper Quote table names. Defaults to column quoting. Closes #4593.
jeremy authored
901 sql = "DELETE FROM #{quoted_table_name} "
c9c1852 David Heinemeier Hansson Making ActiveRecord faster [skaes]
dhh authored
902 add_conditions!(sql, conditions, scope(:find))
db045db David Heinemeier Hansson Initial
dhh authored
903 connection.delete(sql, "#{name} Delete all")
904 end
905
906 # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
907 # 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
908 # using the ActiveRecord::Calculations class methods. Look into those before using this.
909 #
a293278 Pratik Merge docrails
lifo authored
910 # ==== Parameters
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
911 #
dc4eec1 Pratik Merge docrails:
lifo authored
912 # * +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
913 #
914 # ==== Examples
915 #
e17bf81 Jamis Buck Fix typo in count_by_sql documentation #1969 [Alexey Verkhovsky]
jamis authored
916 # Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
db045db David Heinemeier Hansson Initial
dhh authored
917 def count_by_sql(sql)
a775cb1 David Heinemeier Hansson Added the option for sanitizing find_by_sql and the offset parts in regu...
dhh authored
918 sql = sanitize_conditions(sql)
caaf40d David Heinemeier Hansson Added AbstractAdapter#select_value and AbstractAdapter#select_values as ...
dhh authored
919 connection.select_value(sql, "#{name} Count").to_i
db045db David Heinemeier Hansson Initial
dhh authored
920 end
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
921
8375237 Jamis Buck Made increment_counter/decrement_counter play nicely with optimistic loc...
jamis authored
922 # A generic "counter updater" implementation, intended primarily to be
923 # used by increment_counter and decrement_counter, but which may also
924 # be useful on its own. It simply does a direct SQL update for the record
925 # with the given ID, altering the given hash of counters by the amount
926 # given by the corresponding value:
927 #
a293278 Pratik Merge docrails
lifo authored
928 # ==== Parameters
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
929 #
dc4eec1 Pratik Merge docrails:
lifo authored
930 # * +id+ - The id of the object you wish to update a counter on.
931 # * +counters+ - An Array of Hashes containing the names of the fields
932 # to update as keys and the amount to update the field by as values.
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
933 #
6bd7d30 Document options for update_counters. Closes #8091 [fearoffish]
Marcel Molina authored
934 # ==== Examples
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
935 #
936 # # For the Post with id of 5, decrement the comment_count by 1, and
6bd7d30 Document options for update_counters. Closes #8091 [fearoffish]
Marcel Molina authored
937 # # increment the action_count by 1
8375237 Jamis Buck Made increment_counter/decrement_counter play nicely with optimistic loc...
jamis authored
938 # Post.update_counters 5, :comment_count => -1, :action_count => 1
6bd7d30 Document options for update_counters. Closes #8091 [fearoffish]
Marcel Molina authored
939 # # Executes the following SQL:
8375237 Jamis Buck Made increment_counter/decrement_counter play nicely with optimistic loc...
jamis authored
940 # # UPDATE posts
941 # # SET comment_count = comment_count - 1,
942 # # action_count = action_count + 1
943 # # WHERE id = 5
944 def update_counters(id, counters)
945 updates = counters.inject([]) { |list, (counter_name, increment)|
946 sign = increment < 0 ? "-" : "+"
459e581 Emilio Tagua update_counters should update nil values.
miloops authored
947 list << "#{connection.quote_column_name(counter_name)} = COALESCE(#{connection.quote_column_name(counter_name)}, 0) #{sign} #{increment.abs}"
8375237 Jamis Buck Made increment_counter/decrement_counter play nicely with optimistic loc...
jamis authored
948 }.join(", ")
98165fd Jeremy Kemper Consistently quote primary key column names. Closes #7763.
jeremy authored
949 update_all(updates, "#{connection.quote_column_name(primary_key)} = #{quote_value(id)}")
8375237 Jamis Buck Made increment_counter/decrement_counter play nicely with optimistic loc...
jamis authored
950 end
951
15dc567 Also add documentation enhancements for increment_counter. Closes #8092....
Marcel Molina authored
952 # Increment a number field by one, usually representing a count.
953 #
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
954 # This is used for caching aggregate values, so that they don't need to be computed every time.
955 # For example, a DiscussionBoard may cache post_count and comment_count otherwise every time the board is
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobSilv...
Marcel Molina authored
956 # shown it would have to run an SQL query to find how many posts and comments there are.
15dc567 Also add documentation enhancements for increment_counter. Closes #8092....
Marcel Molina authored
957 #
a293278 Pratik Merge docrails
lifo authored
958 # ==== Parameters
15dc567 Also add documentation enhancements for increment_counter. Closes #8092....
Marcel Molina authored
959 #
dc4eec1 Pratik Merge docrails:
lifo authored
960 # * +counter_name+ - The name of the field that should be incremented.
961 # * +id+ - The id of the object that should be incremented.
15dc567 Also add documentation enhancements for increment_counter. Closes #8092....
Marcel Molina authored
962 #
963 # ==== Examples
964 #
965 # # Increment the post_count column for the record with an id of 5
966 # DiscussionBoard.increment_counter(:post_count, 5)
db045db David Heinemeier Hansson Initial
dhh authored
967 def increment_counter(counter_name, id)
8375237 Jamis Buck Made increment_counter/decrement_counter play nicely with optimistic loc...
jamis authored
968 update_counters(id, counter_name => 1)
db045db David Heinemeier Hansson Initial
dhh authored
969 end
970
5bd3570 Enhance documentation for decrement_counter. Closes #8093. [fearoffish]
Marcel Molina authored
971 # Decrement a number field by one, usually representing a count.
972 #
973 # This works the same as increment_counter but reduces the column value by 1 instead of increasing it.
974 #
a293278 Pratik Merge docrails
lifo authored
975 # ==== Parameters
5bd3570 Enhance documentation for decrement_counter. Closes #8093. [fearoffish]
Marcel Molina authored
976 #
dc4eec1 Pratik Merge docrails:
lifo authored
977 # * +counter_name+ - The name of the field that should be decremented.
978 # * +id+ - The id of the object that should be decremented.
5bd3570 Enhance documentation for decrement_counter. Closes #8093. [fearoffish]
Marcel Molina authored
979 #
980 # ==== Examples
981 #
982 # # Decrement the post_count column for the record with an id of 5
983 # DiscussionBoard.decrement_counter(:post_count, 5)
db045db David Heinemeier Hansson Initial
dhh authored
984 def decrement_counter(counter_name, id)
8375237 Jamis Buck Made increment_counter/decrement_counter play nicely with optimistic loc...
jamis authored
985 update_counters(id, counter_name => -1)
db045db David Heinemeier Hansson Initial
dhh authored
986 end
987
c450a36 David Heinemeier Hansson Doc fixes
dhh authored
988
98dc582 Pratik Merge docrails.
lifo authored
989 # Attributes named in this macro are protected from mass-assignment,
990 # such as <tt>new(attributes)</tt>,
991 # <tt>update_attributes(attributes)</tt>, or
992 # <tt>attributes=(attributes)</tt>.
993 #
994 # Mass-assignment to these attributes will simply be ignored, to assign
995 # to them you can use direct writer methods. This is meant to protect
996 # sensitive attributes from being overwritten by malicious users
997 # tampering with URLs or forms.
db045db David Heinemeier Hansson Initial
dhh authored
998 #
999 # class Customer < ActiveRecord::Base
1000 # attr_protected :credit_rating
1001 # end
1002 #
1003 # customer = Customer.new("name" => David, "credit_rating" => "Excellent")
1004 # customer.credit_rating # => nil
1005 # customer.attributes = { "description" => "Jolly fellow", "credit_rating" => "Superb" }
1006 # customer.credit_rating # => nil
1007 #
1008 # customer.credit_rating = "Average"
1009 # customer.credit_rating # => "Average"
d761ac4 Add docs explaining how to protect all attributes using attr_accessible ...
Marcel Molina authored
1010 #
98dc582 Pratik Merge docrails.
lifo authored
1011 # To start from an all-closed default and enable attributes as needed,
1012 # have a look at +attr_accessible+.
db045db David Heinemeier Hansson Initial
dhh authored
1013 def attr_protected(*attributes)
288e947 Clemens Kofler Some performance goodness for inheritable attributes.
clemens authored
1014 write_inheritable_attribute(:attr_protected, Set.new(attributes.map(&:to_s)) + (protected_attributes || []))
db045db David Heinemeier Hansson Initial
dhh authored
1015 end
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
1016
098fa94 David Heinemeier Hansson Fixed documentation snafus #575, #576, #577, #585
dhh authored
1017 # Returns an array of all the attributes that have been protected from mass-assignment.
db045db David Heinemeier Hansson Initial
dhh authored
1018 def protected_attributes # :nodoc:
288e947 Clemens Kofler Some performance goodness for inheritable attributes.
clemens authored
1019 read_inheritable_attribute(:attr_protected)
db045db David Heinemeier Hansson Initial
dhh authored
1020 end
1021
98dc582 Pratik Merge docrails.
lifo authored
1022 # Specifies a white list of model attributes that can be set via
1023 # mass-assignment, such as <tt>new(attributes)</tt>,
1024 # <tt>update_attributes(attributes)</tt>, or
1025 # <tt>attributes=(attributes)</tt>
f770b82 Enhance explanation with more examples for attr_accessible macro. Closes...
Marcel Molina authored
1026 #
98dc582 Pratik Merge docrails.
lifo authored
1027 # This is the opposite of the +attr_protected+ macro: Mass-assignment
1028 # will only set attributes in this list, to assign to the rest of
1029 # attributes you can use direct writer methods. This is meant to protect
1030 # sensitive attributes from being overwritten by malicious users
1031 # tampering with URLs or forms. If you'd rather start from an all-open
1032 # default and restrict attributes as needed, have a look at
1033 # +attr_protected+.
d761ac4 Add docs explaining how to protect all attributes using attr_accessible ...
Marcel Molina authored
1034 #
1035 # class Customer < ActiveRecord::Base
f770b82 Enhance explanation with more examples for attr_accessible macro. Closes...
Marcel Molina authored
1036 # attr_accessible :name, :nickname
d761ac4 Add docs explaining how to protect all attributes using attr_accessible ...
Marcel Molina authored
1037 # end
1038 #
f770b82 Enhance explanation with more examples for attr_accessible macro. Closes...
Marcel Molina authored
1039 # customer = Customer.new(:name => "David", :nickname => "Dave", :credit_rating => "Excellent")
1040 # customer.credit_rating # => nil
1041 # customer.attributes = { :name => "Jolly fellow", :credit_rating => "Superb" }
1042 # customer.credit_rating # => nil
d761ac4 Add docs explaining how to protect all attributes using attr_accessible ...
Marcel Molina authored
1043 #
f770b82 Enhance explanation with more examples for attr_accessible macro. Closes...
Marcel Molina authored
1044 # customer.credit_rating = "Average"
1045 # customer.credit_rating # => "Average"
db045db David Heinemeier Hansson Initial
dhh authored
1046 def attr_accessible(*attributes)
288e947 Clemens Kofler Some performance goodness for inheritable attributes.
clemens authored
1047 write_inheritable_attribute(:attr_accessible, Set.new(attributes.map(&:to_s)) + (accessible_attributes || []))
db045db David Heinemeier Hansson Initial
dhh authored
1048 end
6e39c9e Jeremy Kemper r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
1049
098fa94 David Heinemeier Hansson Fixed documentation snafus #575, #576, #577, #585
dhh authored
1050 # Returns an array of all the attributes that have been made accessible to mass-assignment.
db045db David Heinemeier Hansson Initial
dhh authored
1051 def accessible_attributes # :nodoc:
288e947 Clemens Kofler Some performance goodness for inheritable attributes.
clemens authored
1052 read_inheritable_attribute(:attr_accessible)
db045db David Heinemeier Hansson Initial
dhh authored
1053 end
1054
66d05f5 risk danger olson Add attr_readonly to specify columns that are skipped during a normal Ac...
technoweenie authored
1055 # Attributes listed as readonly can be set for a new record, but will be ignored in database updates afterwards.
1056 def attr_readonly(*attributes)
288e947 Clemens Kofler Some performance goodness for inheritable attributes.
clemens authored
1057 write_inheritable_attribute(:attr_readonly, Set.new(attributes.map(&:to_s)) + (readonly_attributes || []))
66d05f5 risk danger olson Add attr_readonly to specify columns that are skipped during a normal Ac...
technoweenie authored
1058 end
1059
1060 # Returns an array of all the attributes that have been specified as readonly.
1061 def readonly_attributes
288e947 Clemens Kofler Some performance goodness for inheritable attributes.
clemens authored
1062 read_inheritable_attribute(:attr_readonly)
66d05f5 risk danger olson Add attr_readonly to specify columns that are skipped during a normal Ac...
technoweenie authored
1063 end
c450a36 David Heinemeier Hansson Doc fixes
dhh authored
1064
7367325 Jeremy Kemper Document Active Record exceptions. Closes #10444.
jeremy authored
1065 # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object,
1066 # then specify the name of that attribute using this method and it will be handled automatically.
1067 # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that
98dc582 Pratik Merge docrails.
lifo authored
1068 # class on retrieval or SerializationTypeMismatch will be raised.
1a0cdf7 David Heinemeier Hansson Docfix (closes #8096)
dhh authored
1069 #
a293278 Pratik Merge docrails
lifo authored
1070 # ==== Parameters
1a0cdf7 David Heinemeier Hansson Docfix (closes #8096)
dhh authored
1071 #
dc4eec1 Pratik Merge docrails:
lifo authored
1072 # * +attr_name+ - The field name that should be serialized.
1073 # * +class_name+ - Optional, class name that the object