rails / rails

Ruby on Rails

This URL has Read+Write access

db045dbb » dhh 2004-11-23 Initial 1 require 'yaml'
aabf9093 » jeremy 2005-11-02 Correct reader method gener... 2 require 'set'
f5d720fb » jeremy 2009-04-22 Opt in to Dependencies 3 require 'active_support/dependencies'
db045dbb » dhh 2004-11-23 Initial 4
5 module ActiveRecord #:nodoc:
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 6 # Generic Active Record exception class.
73673256 » jeremy 2007-12-09 Document Active Record exce... 7 class ActiveRecordError < StandardError
db045dbb » dhh 2004-11-23 Initial 8 end
73673256 » jeremy 2007-12-09 Document Active Record exce... 9
0432d151 » lifo 2008-07-16 Merge with docrails. Comment 10 # Raised when the single-table inheritance mechanism fails to locate the subclass
73673256 » jeremy 2007-12-09 Document Active Record exce... 11 # (for example due to improper usage of column that +inheritance_column+ points to).
605bc775 » dhh 2004-12-14 Added a better exception fo... 12 class SubclassNotFound < ActiveRecordError #:nodoc:
13 end
73673256 » jeremy 2007-12-09 Document Active Record exce... 14
64092de2 » fxn 2008-05-02 Improve documentation cover... 15 # Raised when an object assigned to an association has an incorrect type.
73673256 » jeremy 2007-12-09 Document Active Record exce... 16 #
64092de2 » fxn 2008-05-02 Improve documentation cover... 17 # class Ticket < ActiveRecord::Base
18 # has_many :patches
19 # end
73673256 » jeremy 2007-12-09 Document Active Record exce... 20 #
64092de2 » fxn 2008-05-02 Improve documentation cover... 21 # class Patch < ActiveRecord::Base
22 # belongs_to :ticket
23 # end
73673256 » jeremy 2007-12-09 Document Active Record exce... 24 #
64092de2 » fxn 2008-05-02 Improve documentation cover... 25 # # Comments are not patches, this assignment raises AssociationTypeMismatch.
26 # @ticket.patches << Comment.new(:content => "Please attach tests to your patch.")
73673256 » jeremy 2007-12-09 Document Active Record exce... 27 class AssociationTypeMismatch < ActiveRecordError
db045dbb » dhh 2004-11-23 Initial 28 end
73673256 » jeremy 2007-12-09 Document Active Record exce... 29
30 # Raised when unserialized object's type mismatches one specified for serializable field.
31 class SerializationTypeMismatch < ActiveRecordError
db045dbb » dhh 2004-11-23 Initial 32 end
73673256 » jeremy 2007-12-09 Document Active Record exce... 33
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 34 # Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt> misses adapter field).
73673256 » jeremy 2007-12-09 Document Active Record exce... 35 class AdapterNotSpecified < ActiveRecordError
db045dbb » dhh 2004-11-23 Initial 36 end
73673256 » jeremy 2007-12-09 Document Active Record exce... 37
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 38 # Raised when Active Record cannot find database adapter specified in <tt>config/database.yml</tt> or programmatically.
73673256 » jeremy 2007-12-09 Document Active Record exce... 39 class AdapterNotFound < ActiveRecordError
db045dbb » dhh 2004-11-23 Initial 40 end
73673256 » jeremy 2007-12-09 Document Active Record exce... 41
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 42 # Raised when connection to the database could not been established (for example when <tt>connection=</tt> is given a nil object).
73673256 » jeremy 2007-12-09 Document Active Record exce... 43 class ConnectionNotEstablished < ActiveRecordError
db045dbb » dhh 2004-11-23 Initial 44 end
73673256 » jeremy 2007-12-09 Document Active Record exce... 45
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 46 # Raised when Active Record cannot find record by given id or set of ids.
73673256 » jeremy 2007-12-09 Document Active Record exce... 47 class RecordNotFound < ActiveRecordError
db045dbb » dhh 2004-11-23 Initial 48 end
73673256 » jeremy 2007-12-09 Document Active Record exce... 49
50 # Raised by ActiveRecord::Base.save! and ActiveRecord::Base.create! methods when record cannot be
51 # saved because record is invalid.
52 class RecordNotSaved < ActiveRecordError
4c7555ae » dhh 2006-02-28 Fixed that Base.save should... 53 end
73673256 » jeremy 2007-12-09 Document Active Record exce... 54
55 # 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).
56 class StatementInvalid < ActiveRecordError
db045dbb » dhh 2004-11-23 Initial 57 end
73673256 » jeremy 2007-12-09 Document Active Record exce... 58
64092de2 » fxn 2008-05-02 Improve documentation cover... 59 # Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example, when using +find+ method)
73673256 » jeremy 2007-12-09 Document Active Record exce... 60 # does not match number of expected variables.
61 #
64092de2 » fxn 2008-05-02 Improve documentation cover... 62 # For example, in
73673256 » jeremy 2007-12-09 Document Active Record exce... 63 #
64092de2 » fxn 2008-05-02 Improve documentation cover... 64 # Location.find :all, :conditions => ["lat = ? AND lng = ?", 53.7362]
73673256 » jeremy 2007-12-09 Document Active Record exce... 65 #
64092de2 » fxn 2008-05-02 Improve documentation cover... 66 # two placeholders are given but only one variable to fill them.
73673256 » jeremy 2007-12-09 Document Active Record exce... 67 class PreparedStatementInvalid < ActiveRecordError
554597d6 » dhh 2004-12-08 Added named bind-style vari... 68 end
73673256 » jeremy 2007-12-09 Document Active Record exce... 69
70 # Raised on attempt to save stale record. Record is stale when it's being saved in another query after
71 # instantiation, for example, when two users edit the same wiki page and one starts editing and saves
72 # the page before the other.
73 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 74 # Read more about optimistic locking in ActiveRecord::Locking module RDoc.
73673256 » jeremy 2007-12-09 Document Active Record exce... 75 class StaleObjectError < ActiveRecordError
fbf9281f » dhh 2004-12-31 Added automated optimistic ... 76 end
73673256 » jeremy 2007-12-09 Document Active Record exce... 77
78 # Raised when association is being configured improperly or
79 # user tries to use offset and limit together with has_many or has_and_belongs_to_many associations.
80 class ConfigurationError < ActiveRecordError
5b9b904f » dhh 2005-07-10 Added support for limit and... 81 end
73673256 » jeremy 2007-12-09 Document Active Record exce... 82
83 # Raised on attempt to update record that is instantiated as read only.
84 class ReadOnlyRecord < ActiveRecordError
64fcb752 » jeremy 2005-10-14 r3618@sedna: jeremy | 200... 85 end
73673256 » jeremy 2007-12-09 Document Active Record exce... 86
6e754551 » lifo 2008-07-28 Merge docrails changes 87 # ActiveRecord::Transactions::ClassMethods.transaction uses this exception
88 # to distinguish a deliberate rollback from other exceptional situations.
89 # Normally, raising an exception will cause the +transaction+ method to rollback
90 # the database transaction *and* pass on the exception. But if you raise an
91 # ActiveRecord::Rollback exception, then the database transaction will be rolled back,
92 # without passing on the exception.
93 #
94 # For example, you could do this in your controller to rollback a transaction:
95 #
96 # class BooksController < ActionController::Base
97 # def create
98 # Book.transaction do
99 # book = Book.new(params[:book])
100 # book.save!
101 # if today_is_friday?
102 # # The system must fail on Friday so that our support department
103 # # won't be out of job. We silently rollback this transaction
104 # # without telling the user.
105 # raise ActiveRecord::Rollback, "Call tech support!"
106 # end
107 # end
108 # # ActiveRecord::Rollback is the only exception that won't be passed on
109 # # by ActiveRecord::Base.transaction, so this line will still be reached
110 # # even on Friday.
111 # redirect_to root_url
112 # end
113 # end
73673256 » jeremy 2007-12-09 Document Active Record exce... 114 class Rollback < ActiveRecordError
5b2e8b1e » technoweenie 2007-10-05 Fix that ActiveRecord would... 115 end
73673256 » jeremy 2007-12-09 Document Active Record exce... 116
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 117 # Raised when attribute has a name reserved by Active Record (when attribute has name of one of Active Record instance methods).
73673256 » jeremy 2007-12-09 Document Active Record exce... 118 class DangerousAttributeError < ActiveRecordError
ebbe4fb0 » NZKoz 2007-05-17 Replace the transaction {|t... 119 end
84a14f26 » jeremy 2007-10-07 Raise ProtectedAttributeAss... 120
dc4eec11 » lifo 2008-05-09 Merge docrails: 121 # Raised when you've tried to access a column which wasn't loaded by your finder.
122 # Typically this is because <tt>:select</tt> has been specified.
5b801b59 » NZKoz 2007-08-14 Change the implementation o... 123 class MissingAttributeError < NoMethodError
124 end
e48b062e » jeremy 2007-05-17 Sanitize Base#inspect. Clos... 125
4f687529 » jeremy 2008-09-08 Revert "Revert "Raise Unkno... 126 # Raised when unknown attributes are supplied via mass assignment.
127 class UnknownAttributeError < NoMethodError
128 end
129
0432d151 » lifo 2008-07-16 Merge with docrails. Comment 130 # Raised when an error occurred while doing a mass assignment to an attribute through the
dc4eec11 » lifo 2008-05-09 Merge docrails: 131 # <tt>attributes=</tt> method. The exception has an +attribute+ property that is the name of the
132 # offending attribute.
133 class AttributeAssignmentError < ActiveRecordError
d2fefbe9 » dhh 2005-03-06 Added MultiparameterAssignm... 134 attr_reader :exception, :attribute
135 def initialize(message, exception, attribute)
136 @exception = exception
137 @attribute = attribute
138 @message = message
139 end
140 end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 141
dc4eec11 » lifo 2008-05-09 Merge docrails: 142 # Raised when there are multiple errors while doing a mass assignment through the +attributes+
143 # method. The exception has an +errors+ property that contains an array of AttributeAssignmentError
144 # objects, each corresponding to the error while assigning to an attribute.
145 class MultiparameterAssignmentErrors < ActiveRecordError
d2fefbe9 » dhh 2005-03-06 Added MultiparameterAssignm... 146 attr_reader :errors
147 def initialize(errors)
148 @errors = errors
149 end
150 end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 151
2948910b » Marcel Molina 2005-10-10 Misc doc fixes (typos/gramm... 152 # Active Record objects don't specify their attributes directly, but rather infer them from the table definition with
db045dbb » dhh 2004-11-23 Initial 153 # which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change
154 # is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 155 # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
156 #
db045dbb » dhh 2004-11-23 Initial 157 # See the mapping rules in table_name and the full example in link:files/README.html for more insight.
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 158 #
db045dbb » dhh 2004-11-23 Initial 159 # == Creation
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 160 #
2948910b » Marcel Molina 2005-10-10 Misc doc fixes (typos/gramm... 161 # Active Records accept constructor parameters either in a hash or as a block. The hash method is especially useful when
7143d801 » Marcel Molina 2007-11-07 Smattering of grammatical f... 162 # you're receiving the data from somewhere else, like an HTTP request. It works like this:
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 163 #
0591c53e » dhh 2005-04-17 Made the dynamic finders us... 164 # user = User.new(:name => "David", :occupation => "Code Artist")
db045dbb » dhh 2004-11-23 Initial 165 # user.name # => "David"
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 166 #
db045dbb » dhh 2004-11-23 Initial 167 # You can also use block initialization:
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 168 #
db045dbb » dhh 2004-11-23 Initial 169 # user = User.new do |u|
170 # u.name = "David"
171 # u.occupation = "Code Artist"
172 # end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 173 #
db045dbb » dhh 2004-11-23 Initial 174 # And of course you can just create a bare object and specify the attributes after the fact:
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 175 #
db045dbb » dhh 2004-11-23 Initial 176 # user = User.new
177 # user.name = "David"
178 # user.occupation = "Code Artist"
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 179 #
db045dbb » dhh 2004-11-23 Initial 180 # == Conditions
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 181 #
c5ec16e5 » dhh 2006-06-03 Added simple hash condition... 182 # Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement.
db045dbb » dhh 2004-11-23 Initial 183 # The array form is to be used when the condition input is tainted and requires sanitization. The string form can
c5ec16e5 » dhh 2006-06-03 Added simple hash condition... 184 # be used for statements that don't involve tainted data. The hash form works much like the array form, except
28767075 » jeremy 2007-01-10 Pass a range in :conditions... 185 # only equality and range is possible. Examples:
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 186 #
48052d70 » jeremy 2006-06-02 to_xml fixes, features, and... 187 # class User < ActiveRecord::Base
db045dbb » dhh 2004-11-23 Initial 188 # def self.authenticate_unsafely(user_name, password)
3dfa56cc » dhh 2005-06-26 Updated all references to t... 189 # find(:first, :conditions => "user_name = '#{user_name}' AND password = '#{password}'")
db045dbb » dhh 2004-11-23 Initial 190 # end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 191 #
db045dbb » dhh 2004-11-23 Initial 192 # def self.authenticate_safely(user_name, password)
3dfa56cc » dhh 2005-06-26 Updated all references to t... 193 # find(:first, :conditions => [ "user_name = ? AND password = ?", user_name, password ])
db045dbb » dhh 2004-11-23 Initial 194 # end
c5ec16e5 » dhh 2006-06-03 Added simple hash condition... 195 #
196 # def self.authenticate_safely_simply(user_name, password)
197 # find(:first, :conditions => { :user_name => user_name, :password => password })
198 # end
db045dbb » dhh 2004-11-23 Initial 199 # end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 200 #
2575b3b0 » dhh 2004-12-06 Added extra words of cautio... 201 # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection
7143d801 » Marcel Molina 2007-11-07 Smattering of grammatical f... 202 # attacks if the <tt>user_name</tt> and +password+ parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and
73673256 » jeremy 2007-12-09 Document Active Record exce... 203 # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+ before inserting them in the query,
c5ec16e5 » dhh 2006-06-03 Added simple hash condition... 204 # which will ensure that an attacker can't escape the query and fake the login (or worse).
2575b3b0 » dhh 2004-12-06 Added extra words of cautio... 205 #
5cd38ca2 » dhh 2005-03-27 Added documentation about n... 206 # When using multiple parameters in the conditions, it can easily become hard to read exactly what the fourth or fifth
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 207 # question mark is supposed to represent. In those cases, you can resort to named bind variables instead. That's done by replacing
5cd38ca2 » dhh 2005-03-27 Added documentation about n... 208 # the question marks with symbols and supplying a hash with values for the matching symbol keys:
209 #
a7e6e009 » Marcel Molina 2007-12-05 Documentation for find inco... 210 # Company.find(:first, :conditions => [
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 211 # "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
5cd38ca2 » dhh 2005-03-27 Added documentation about n... 212 # { :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' }
213 # ])
214 #
c5ec16e5 » dhh 2006-06-03 Added simple hash condition... 215 # Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
216 # operator. For instance:
217 #
218 # Student.find(:all, :conditions => { :first_name => "Harvey", :status => 1 })
219 # Student.find(:all, :conditions => params[:student])
220 #
28767075 » jeremy 2007-01-10 Pass a range in :conditions... 221 # A range may be used in the hash to use the SQL BETWEEN operator:
222 #
223 # Student.find(:all, :conditions => { :grade => 9..12 })
c5ec16e5 » dhh 2006-06-03 Added simple hash condition... 224 #
aa4af60a » lifo 2008-04-04 Improve documentation. 225 # An array may be used in the hash to use the SQL IN operator:
226 #
227 # Student.find(:all, :conditions => { :grade => [9,11,12] })
228 #
db045dbb » dhh 2004-11-23 Initial 229 # == Overwriting default accessors
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 230 #
7143d801 » Marcel Molina 2007-11-07 Smattering of grammatical f... 231 # All column values are automatically available through basic accessors on the Active Record object, but sometimes you
232 # want to specialize this behavior. This can be done by overwriting the default accessors (using the same
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 233 # name as the attribute) and calling <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually change things.
db045dbb » dhh 2004-11-23 Initial 234 # Example:
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 235 #
db045dbb » dhh 2004-11-23 Initial 236 # class Song < ActiveRecord::Base
237 # # Uses an integer of seconds to hold the length of the song
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 238 #
db045dbb » dhh 2004-11-23 Initial 239 # def length=(minutes)
64092de2 » fxn 2008-05-02 Improve documentation cover... 240 # write_attribute(:length, minutes.to_i * 60)
db045dbb » dhh 2004-11-23 Initial 241 # end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 242 #
db045dbb » dhh 2004-11-23 Initial 243 # def length
0591c53e » dhh 2005-04-17 Made the dynamic finders us... 244 # read_attribute(:length) / 60
db045dbb » dhh 2004-11-23 Initial 245 # end
246 # end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 247 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 248 # You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt> instead of <tt>write_attribute(:attribute, value)</tt> and
249 # <tt>read_attribute(:attribute)</tt> as a shorter form.
0591c53e » dhh 2005-04-17 Made the dynamic finders us... 250 #
e4d845ef » Marcel Molina 2007-12-05 Document automatically gene... 251 # == Attribute query methods
252 #
253 # In addition to the basic accessors, query methods are also automatically available on the Active Record object.
254 # Query methods allow you to test whether an attribute value is present.
73673256 » jeremy 2007-12-09 Document Active Record exce... 255 #
e4d845ef » Marcel Molina 2007-12-05 Document automatically gene... 256 # For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
257 # to determine whether the user has a name:
258 #
259 # user = User.new(:name => "David")
260 # user.name? # => true
261 #
262 # anonymous = User.new(:name => "")
263 # anonymous.name? # => false
264 #
2948910b » Marcel Molina 2005-10-10 Misc doc fixes (typos/gramm... 265 # == Accessing attributes before they have been typecasted
4eab3758 » dhh 2005-02-23 Finished polishing API docs 266 #
2948910b » Marcel Molina 2005-10-10 Misc doc fixes (typos/gramm... 267 # Sometimes you want to be able to read the raw attribute data without having the column-determined typecast run its course first.
dc4eec11 » lifo 2008-05-09 Merge docrails: 268 # That can be done by using the <tt><attribute>_before_type_cast</tt> accessors that all attributes have. For example, if your Account model
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 269 # has a <tt>balance</tt> attribute, you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>.
4eab3758 » dhh 2005-02-23 Finished polishing API docs 270 #
271 # This is especially useful in validation situations where the user might supply a string for an integer field and you want to display
2948910b » Marcel Molina 2005-10-10 Misc doc fixes (typos/gramm... 272 # the original string back in an error message. Accessing the attribute normally would typecast the string to 0, which isn't what you
4eab3758 » dhh 2005-02-23 Finished polishing API docs 273 # want.
274 #
ac8fd7df » dhh 2005-01-02 Added dynamic attribute-bas... 275 # == Dynamic attribute-based finders
276 #
a5a82d97 » dhh 2005-11-04 Added extension capabilitie... 277 # Dynamic attribute-based finders are a cleaner way of getting (and/or creating) objects by simple queries without turning to SQL. They work by
6dc9173a » dhh 2008-09-09 Missing doc updates 278 # 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>,
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 279 # <tt>Person.find_all_by_last_name</tt>, and <tt>Payment.find_by_transaction_id</tt>. So instead of writing
a7e6e009 » Marcel Molina 2007-12-05 Documentation for find inco... 280 # <tt>Person.find(:first, :conditions => ["user_name = ?", user_name])</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
281 # 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>.
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 282 #
ac8fd7df » dhh 2005-01-02 Added dynamic attribute-bas... 283 # It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like
284 # <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
a7e6e009 » Marcel Molina 2007-12-05 Documentation for find inco... 285 # <tt>Person.find(:first, :conditions => ["user_name = ? AND password = ?", user_name, password])</tt>, you just do
ac8fd7df » dhh 2005-01-02 Added dynamic attribute-bas... 286 # <tt>Person.find_by_user_name_and_password(user_name, password)</tt>.
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 287 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 288 # 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>
289 # is actually <tt>Payment.find_all_by_amount(amount, options)</tt>. And the full interface to <tt>Person.find_by_user_name</tt> is
64092de2 » fxn 2008-05-02 Improve documentation cover... 290 # 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>.
567392bf » miloops 2008-09-01 Added find_last_by dynamic ... 291 # Also you may call <tt>Payment.find_last_by_amount(amount, options)</tt> returning the last record matching that amount and options.
959f362a » dhh 2005-01-02 Added find_all style to the... 292 #
a5a82d97 » dhh 2005-11-04 Added extension capabilitie... 293 # The same dynamic finder style can be used to create the object if it doesn't already exist. This dynamic finder is called with
5c47ceb3 » NZKoz 2008-03-25 Typo fix in documentation f... 294 # <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:
a5a82d97 » dhh 2005-11-04 Added extension capabilitie... 295 #
296 # # No 'Summer' tag exists
297 # Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
73673256 » jeremy 2007-12-09 Document Active Record exce... 298 #
a5a82d97 » dhh 2005-11-04 Added extension capabilitie... 299 # # Now the 'Summer' tag does exist
300 # Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
301 #
c10b2255 » dhh 2008-03-25 Fixed that ActiveRecord#Bas... 302 # # Now 'Bob' exist and is an 'admin'
303 # User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }
304 #
0432d151 » lifo 2008-07-16 Merge with docrails. Comment 305 # 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:
d19e4642 » sstephenson 2006-06-20 Added find_or_initialize_by... 306 #
307 # # No 'Winter' tag exists
308 # winter = Tag.find_or_initialize_by_name("Winter")
85fbb22f » dhh 2006-09-05 Backed out of new_record? t... 309 # winter.new_record? # true
d19e4642 » sstephenson 2006-06-20 Added find_or_initialize_by... 310 #
14cc8d2f » jeremy 2007-03-13 find_or_create_by_* takes a... 311 # To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of
312 # a list of parameters. For example:
313 #
314 # Tag.find_or_create_by_name(:name => "rails", :creator => current_user)
315 #
316 # That will either find an existing tag named "rails", or create a new one while setting the user that created it.
317 #
098fa943 » dhh 2005-02-07 Fixed documentation snafus ... 318 # == Saving arrays, hashes, and other non-mappable objects in text columns
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 319 #
320 # 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+.
2948910b » Marcel Molina 2005-10-10 Misc doc fixes (typos/gramm... 321 # This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work. Example:
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 322 #
db045dbb » dhh 2004-11-23 Initial 323 # class User < ActiveRecord::Base
324 # serialize :preferences
325 # end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 326 #
ca2eb16b » Marcel Molina 2006-04-26 Fix syntax error in documen... 327 # user = User.create(:preferences => { "background" => "black", "display" => large })
db045dbb » dhh 2004-11-23 Initial 328 # User.find(user.id).preferences # => { "background" => "black", "display" => large }
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 329 #
2948910b » Marcel Molina 2005-10-10 Misc doc fixes (typos/gramm... 330 # You can also specify a class option as the second parameter that'll raise an exception if a serialized object is retrieved as a
39e1ac65 » lifo 2009-01-18 Merge docrails 331 # descendant of a class not in the hierarchy. Example:
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 332 #
db045dbb » dhh 2004-11-23 Initial 333 # class User < ActiveRecord::Base
66f44e6c » dhh 2005-01-25 Updated documentation for s... 334 # serialize :preferences, Hash
db045dbb » dhh 2004-11-23 Initial 335 # end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 336 #
0591c53e » dhh 2005-04-17 Made the dynamic finders us... 337 # user = User.create(:preferences => %w( one two three ))
db045dbb » dhh 2004-11-23 Initial 338 # User.find(user.id).preferences # raises SerializationTypeMismatch
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 339 #
db045dbb » dhh 2004-11-23 Initial 340 # == Single table inheritance
341 #
7143d801 » Marcel Molina 2007-11-07 Smattering of grammatical f... 342 # Active Record allows inheritance by storing the name of the class in a column that by default is named "type" (can be changed
db045dbb » dhh 2004-11-23 Initial 343 # by overwriting <tt>Base.inheritance_column</tt>). This means that an inheritance looking like this:
344 #
345 # class Company < ActiveRecord::Base; end
346 # class Firm < Company; end
347 # class Client < Company; end
348 # class PriorityClient < Client; end
349 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 350 # When you do <tt>Firm.create(:name => "37signals")</tt>, this record will be saved in the companies table with type = "Firm". You can then
351 # fetch this row again using <tt>Company.find(:first, "name = '37signals'")</tt> and it will return a Firm object.
db045dbb » dhh 2004-11-23 Initial 352 #
f033833f » dhh 2004-12-16 Improving documentation... 353 # 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
354 # like normal subclasses with no special magic for differentiating between them or reloading the right type with find.
355 #
db045dbb » dhh 2004-11-23 Initial 356 # Note, all the attributes for all the cases are kept in the same table. Read more:
357 # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 358 #
db045dbb » dhh 2004-11-23 Initial 359 # == Connection to multiple databases in different models
360 #
361 # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection.
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 362 # All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection.
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 363 # For example, if Course is an ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
364 # and Course and all of its subclasses will use this connection instead.
db045dbb » dhh 2004-11-23 Initial 365 #
366 # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is
367 # requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool.
368 #
369 # == Exceptions
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 370 #
dc4eec11 » lifo 2008-05-09 Merge docrails: 371 # * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record.
372 # * AdapterNotSpecified - The configuration hash used in <tt>establish_connection</tt> didn't include an
db045dbb » dhh 2004-11-23 Initial 373 # <tt>:adapter</tt> key.
dc4eec11 » lifo 2008-05-09 Merge docrails: 374 # * AdapterNotFound - The <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a non-existent adapter
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 375 # (or a bad spelling of an existing one).
dc4eec11 » lifo 2008-05-09 Merge docrails: 376 # * AssociationTypeMismatch - The object assigned to the association wasn't of the type specified in the association definition.
377 # * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
378 # * ConnectionNotEstablished+ - No connection has been established. Use <tt>establish_connection</tt> before querying.
379 # * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
380 # or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
381 # nothing was found, please check its documentation for further details.
382 # * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
383 # * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the
384 # <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of AttributeAssignmentError
d2fefbe9 » dhh 2005-03-06 Added MultiparameterAssignm... 385 # objects that should be inspected to determine which attributes triggered the errors.
dc4eec11 » lifo 2008-05-09 Merge docrails: 386 # * AttributeAssignmentError - An error occurred while doing a mass assignment through the <tt>attributes=</tt> method.
d2fefbe9 » dhh 2005-03-06 Added MultiparameterAssignm... 387 # You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error.
57070277 » dhh 2005-09-11 Added better exception erro... 388 #
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 389 # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
dc4eec11 » lifo 2008-05-09 Merge docrails: 390 # So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all
db045dbb » dhh 2004-11-23 Initial 391 # instances in the current object space.
392 class Base
dbbae5e0 » lifo 2008-12-06 Merge with docrails 393 ##
394 # :singleton-method:
db045dbb » dhh 2004-11-23 Initial 395 # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed
396 # on to any new database connections made and which can be retrieved on both a class and instance level by calling +logger+.
1a11bffd » technoweenie 2007-01-27 Don't create instance write... 397 cattr_accessor :logger, :instance_writer => false
e6941149 » jeremy 2007-09-13 Deprecation: removed Reload... 398
db045dbb » dhh 2004-11-23 Initial 399 def self.inherited(child) #:nodoc:
400 @@subclasses[self] ||= []
401 @@subclasses[self] << child
402 super
403 end
e6941149 » jeremy 2007-09-13 Deprecation: removed Reload... 404
fed7d334 » dhh 2006-03-27 Fixed documentation 405 def self.reset_subclasses #:nodoc:
bfbf6bba » jamis 2005-10-15 Allow ARStore::Session to i... 406 nonreloadables = []
e7f61eab » jamis 2005-10-15 squash the memleak in dev m... 407 subclasses.each do |klass|
c08547d2 » josh 2008-06-03 Namespace Inflector, Depend... Comment 408 unless ActiveSupport::Dependencies.autoloaded? klass
bfbf6bba » jamis 2005-10-15 Allow ARStore::Session to i... 409 nonreloadables << klass
410 next
411 end
e7f61eab » jamis 2005-10-15 squash the memleak in dev m... 412 klass.instance_variables.each { |var| klass.send(:remove_instance_variable, var) }
413 klass.instance_methods(false).each { |m| klass.send :undef_method, m }
414 end
bfbf6bba » jamis 2005-10-15 Allow ARStore::Session to i... 415 @@subclasses = {}
416 nonreloadables.each { |klass| (@@subclasses[klass.superclass] ||= []) << klass }
3c0129af » dhh 2005-09-20 Fixed memory leak with Acti... 417 end
418
db045dbb » dhh 2004-11-23 Initial 419 @@subclasses = {}
c3aa2bcd » Manfred 2009-03-10 Ensure nested with_scope me... 420
dbbae5e0 » lifo 2008-12-06 Merge with docrails 421 ##
422 # :singleton-method:
a2932784 » lifo 2008-10-05 Merge docrails 423 # Contains the database configuration - as is typically stored in config/database.yml -
424 # as a Hash.
425 #
426 # For example, the following database.yml...
427 #
428 # development:
429 # adapter: sqlite3
430 # database: db/development.sqlite3
431 #
432 # production:
433 # adapter: sqlite3
434 # database: db/production.sqlite3
435 #
436 # ...would result in ActiveRecord::Base.configurations to look like this:
437 #
438 # {
439 # 'development' => {
440 # 'adapter' => 'sqlite3',
441 # 'database' => 'db/development.sqlite3'
442 # },
443 # 'production' => {
444 # 'adapter' => 'sqlite3',
445 # 'database' => 'db/production.sqlite3'
446 # }
447 # }
1a11bffd » technoweenie 2007-01-27 Don't create instance write... 448 cattr_accessor :configurations, :instance_writer => false
c4a36349 » jeremy 2005-06-12 Corrected @@configurations ... 449 @@configurations = {}
450
dbbae5e0 » lifo 2008-12-06 Merge with docrails 451 ##
452 # :singleton-method:
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 453 # Accessor for the prefix type that will be prepended to every primary key column name. The options are :table_name and
db045dbb » dhh 2004-11-23 Initial 454 # :table_name_with_underscore. If the first is specified, the Product class will look for "productid" instead of "id" as
455 # the primary column. If the latter is specified, the Product class will look for "product_id" instead of "id". Remember
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 456 # that this is a global setting for all Active Records.
1a11bffd » technoweenie 2007-01-27 Don't create instance write... 457 cattr_accessor :primary_key_prefix_type, :instance_writer => false
db045dbb » dhh 2004-11-23 Initial 458 @@primary_key_prefix_type = nil
459
dbbae5e0 » lifo 2008-12-06 Merge with docrails 460 ##
461 # :singleton-method:
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 462 # Accessor for the name of the prefix string to prepend to every table name. So if set to "basecamp_", all
098fa943 » dhh 2005-02-07 Fixed documentation snafus ... 463 # table names will be named like "basecamp_projects", "basecamp_people", etc. This is a convenient way of creating a namespace
db045dbb » dhh 2004-11-23 Initial 464 # for tables in a shared database. By default, the prefix is the empty string.
1a11bffd » technoweenie 2007-01-27 Don't create instance write... 465 cattr_accessor :table_name_prefix, :instance_writer => false
db045dbb » dhh 2004-11-23 Initial 466 @@table_name_prefix = ""
467
dbbae5e0 » lifo 2008-12-06 Merge with docrails 468 ##
469 # :singleton-method:
db045dbb » dhh 2004-11-23 Initial 470 # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
471 # "people_basecamp"). By default, the suffix is the empty string.
1a11bffd » technoweenie 2007-01-27 Don't create instance write... 472 cattr_accessor :table_name_suffix, :instance_writer => false
db045dbb » dhh 2004-11-23 Initial 473 @@table_name_suffix = ""
474
dbbae5e0 » lifo 2008-12-06 Merge with docrails 475 ##
476 # :singleton-method:
84a14f26 » jeremy 2007-10-07 Raise ProtectedAttributeAss... 477 # Indicates whether table names should be the pluralized versions of the corresponding class names.
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 478 # If true, the default table name for a Product class will be +products+. If false, it would just be +product+.
db045dbb » dhh 2004-11-23 Initial 479 # See table_name for the full rules on table/class naming. This is true, by default.
1a11bffd » technoweenie 2007-01-27 Don't create instance write... 480 cattr_accessor :pluralize_table_names, :instance_writer => false
db045dbb » dhh 2004-11-23 Initial 481 @@pluralize_table_names = true
482
dbbae5e0 » lifo 2008-12-06 Merge with docrails 483 ##
484 # :singleton-method:
84a14f26 » jeremy 2007-10-07 Raise ProtectedAttributeAss... 485 # Determines whether to use ANSI codes to colorize the logging statements committed by the connection adapter. These colors
2948910b » Marcel Molina 2005-10-10 Misc doc fixes (typos/gramm... 486 # make it much easier to overview things during debugging (when used through a reader like +tail+ and on a black background), but
911614df » dhh 2005-03-06 Added ActiveRecord::Base.co... 487 # may complicate matters if you use software like syslog. This is true, by default.
1a11bffd » technoweenie 2007-01-27 Don't create instance write... 488 cattr_accessor :colorize_logging, :instance_writer => false
911614df » dhh 2005-03-06 Added ActiveRecord::Base.co... 489 @@colorize_logging = true
490
dbbae5e0 » lifo 2008-12-06 Merge with docrails 491 ##
492 # :singleton-method:
60de8c11 » dhh 2004-12-28 Added Base.default_timezone... 493 # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates and times from the database.
494 # This is set to :local by default.
1a11bffd » technoweenie 2007-01-27 Don't create instance write... 495 cattr_accessor :default_timezone, :instance_writer => false
60de8c11 » dhh 2004-12-28 Added Base.default_timezone... 496 @@default_timezone = :local
d8641ca3 » jeremy 2006-03-01 CHANGED DEFAULT: set Active... 497
dbbae5e0 » lifo 2008-12-06 Merge with docrails 498 ##
499 # :singleton-method:
24c3599c » sstephenson 2005-10-12 Support using different dat... 500 # Specifies the format to use when dumping the database schema with Rails'
501 # Rakefile. If :sql, the schema is dumped as (potentially database-
73673256 » jeremy 2007-12-09 Document Active Record exce... 502 # specific) SQL statements. If :ruby, the schema is dumped as an
24c3599c » sstephenson 2005-10-12 Support using different dat... 503 # ActiveRecord::Schema file which can be loaded into any database that
504 # supports migrations. Use :ruby if you want to have different database
505 # adapters for, e.g., your development and test environments.
1a11bffd » technoweenie 2007-01-27 Don't create instance write... 506 cattr_accessor :schema_format , :instance_writer => false
660952e5 » dhh 2006-02-26 CHANGED DEFAULT: ActiveReco... 507 @@schema_format = :ruby
3b0e1d90 » josh 2008-05-14 Prefer string core_ext infl... Comment 508
dbbae5e0 » lifo 2008-12-06 Merge with docrails 509 ##
510 # :singleton-method:
bbab6391 » codetocustomer 2008-07-16 Set config.active_record.ti... 511 # Specify whether or not to use timestamps for migration numbers
512 cattr_accessor :timestamped_migrations , :instance_writer => false
513 @@timestamped_migrations = true
514
bca8751e » divoxx 2008-04-11 Add ActiveRecord option to ... Comment 515 # Determine whether to store the full constant name including namespace when using STI
516 superclass_delegating_accessor :store_full_sti_class
517 self.store_full_sti_class = false
3b0e1d90 » josh 2008-05-14 Prefer string core_ext infl... Comment 518
2530d0ee » lifo 2008-11-16 Added default_scope to Base... Comment 519 # Stores the default scope for the class
520 class_inheritable_accessor :default_scoping, :instance_writer => false
521 self.default_scoping = []
522
db045dbb » dhh 2004-11-23 Initial 523 class << self # Class methods
d5a4d5ab » dhh 2008-03-12 Added ActiveRecord::Base.fi... 524 # Find operates with four different retrieval approaches:
76690111 » dhh 2005-04-17 Fixes for postgresql testin... 525 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 526 # * 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]).
76690111 » dhh 2005-04-17 Fixes for postgresql testin... 527 # If no record can be found for all of the listed ids, then RecordNotFound will be raised.
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 528 # * Find first - This will return the first record matched by the options used. These options can either be specific
529 # conditions or merely an order. If no record can be matched, +nil+ is returned. Use
530 # <tt>Model.find(:first, *args)</tt> or its shortcut <tt>Model.first(*args)</tt>.
531 # * Find last - This will return the last record matched by the options used. These options can either be specific
532 # conditions or merely an order. If no record can be matched, +nil+ is returned. Use
533 # <tt>Model.find(:last, *args)</tt> or its shortcut <tt>Model.last(*args)</tt>.
534 # * Find all - This will return all the records matched by the options used.
535 # If no records are found, an empty array is returned. Use
536 # <tt>Model.find(:all, *args)</tt> or its shortcut <tt>Model.all(*args)</tt>.
537 #
538 # All approaches accept an options hash as their last parameter.
539 #
a2932784 » lifo 2008-10-05 Merge docrails 540 # ==== Parameters
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 541 #
9cb54008 » lifo 2008-10-16 Merge docrails 542 # * <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.
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 543 # * <tt>:order</tt> - An SQL fragment like "created_at DESC, name".
544 # * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
97403ad5 » miloops 2008-11-21 Add :having option to find,... 545 # * <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.
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 546 # * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned.
547 # * <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.
39e1ac65 » lifo 2009-01-18 Merge docrails 548 # * <tt>:joins</tt> - Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed),
549 # 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),
550 # or an array containing a mixture of both strings and named associations.
9661395d » Marcel Molina 2007-12-13 Remove references to nonexi... 551 # 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.
64092de2 » fxn 2008-05-02 Improve documentation cover... 552 # Pass <tt>:readonly => false</tt> to override.
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 553 # * <tt>:include</tt> - Names associations that should be loaded alongside. The symbols named refer
515886a5 » dhh 2005-04-18 Added documentation for new... 554 # to already defined associations. See eager loading under Associations.
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 555 # * <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
6ef35461 » lifo 2008-09-03 Merge docrails 556 # include the joined columns. Takes a string with the SELECT SQL fragment (e.g. "id, name").
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 557 # * <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
73673256 » jeremy 2007-12-09 Document Active Record exce... 558 # of a database view).
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 559 # * <tt>:readonly</tt> - Mark the returned records read-only so they cannot be saved or updated.
560 # * <tt>:lock</tt> - An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE".
64092de2 » fxn 2008-05-02 Improve documentation cover... 561 # <tt>:lock => true</tt> gives connection's default exclusive lock, usually "FOR UPDATE".
76690111 » dhh 2005-04-17 Fixes for postgresql testin... 562 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 563 # ==== Examples
564 #
565 # # find by id
db045dbb » dhh 2004-11-23 Initial 566 # Person.find(1) # returns the object for ID = 1
567 # Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
568 # Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
7143d801 » Marcel Molina 2007-11-07 Smattering of grammatical f... 569 # Person.find([1]) # returns an array for the object with ID = 1
515886a5 » dhh 2005-04-18 Added documentation for new... 570 # Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
571 #
1e9e198c » jeremy 2007-03-06 Note that find results may ... 572 # Note that returned records may not be in the same order as the ids you
64092de2 » fxn 2008-05-02 Improve documentation cover... 573 # provide since database rows are unordered. Give an explicit <tt>:order</tt>
1e9e198c » jeremy 2007-03-06 Note that find results may ... 574 # to ensure the results are sorted.
575 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 576 # ==== Examples
577 #
578 # # find first
7d010055 » dhh 2005-04-18 Fixed documentation and pre... 579 # Person.find(:first) # returns the first object fetched by SELECT * FROM people
515886a5 » dhh 2005-04-18 Added documentation for new... 580 # Person.find(:first, :conditions => [ "user_name = ?", user_name])
9cb54008 » lifo 2008-10-16 Merge docrails 581 # Person.find(:first, :conditions => [ "user_name = :u", { :u => user_name }])
515886a5 » dhh 2005-04-18 Added documentation for new... 582 # Person.find(:first, :order => "created_on DESC", :offset => 5)
583 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 584 # # find last
d5a4d5ab » dhh 2008-03-12 Added ActiveRecord::Base.fi... 585 # Person.find(:last) # returns the last object fetched by SELECT * FROM people
586 # Person.find(:last, :conditions => [ "user_name = ?", user_name])
587 # Person.find(:last, :order => "created_on DESC", :offset => 5)
588 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 589 # # find all
7d010055 » dhh 2005-04-18 Fixed documentation and pre... 590 # Person.find(:all) # returns an array of objects for all the rows fetched by SELECT * FROM people
515886a5 » dhh 2005-04-18 Added documentation for new... 591 # Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50)
aa4af60a » lifo 2008-04-04 Improve documentation. 592 # Person.find(:all, :conditions => { :friends => ["Bob", "Steve", "Fred"] }
515886a5 » dhh 2005-04-18 Added documentation for new... 593 # Person.find(:all, :offset => 10, :limit => 10)
594 # Person.find(:all, :include => [ :account, :friends ])
33092681 » jeremy 2005-11-10 Add :group option, correspo... 595 # Person.find(:all, :group => "category")
15aa6e05 » jeremy 2006-06-19 r4644@asus: jeremy | 2006... 596 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 597 # Example for find with a lock: Imagine two concurrent transactions:
598 # each will read <tt>person.visits == 2</tt>, add 1 to it, and save, resulting
599 # in two saves of <tt>person.visits = 3</tt>. By locking the row, the second
15aa6e05 » jeremy 2006-06-19 r4644@asus: jeremy | 2006... 600 # transaction has to wait until the first is finished; we get the
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 601 # expected <tt>person.visits == 4</tt>.
602 #
15aa6e05 » jeremy 2006-06-19 r4644@asus: jeremy | 2006... 603 # Person.transaction do
604 # person = Person.find(1, :lock => true)
605 # person.visits += 1
606 # person.save!
607 # end
6bd672eb » dhh 2005-01-01 Added that Base#find takes ... 608 def find(*args)
edd68a58 » dhh 2007-07-24 Refactored in use of extrac... 609 options = args.extract_options!
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 610 validate_find_options(options)
611 set_readonly_option!(options)
64fcb752 » jeremy 2005-10-14 r3618@sedna: jeremy | 200... 612
abc895b8 » dhh 2005-04-03 Added new Base.find API and... 613 case args.first
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 614 when :first then find_initial(options)
d5a4d5ab » dhh 2008-03-12 Added ActiveRecord::Base.fi... 615 when :last then find_last(options)
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 616 when :all then find_every(options)
617 else find_from_ids(args, options)
db045dbb » dhh 2004-11-23 Initial 618 end
619 end
3b0e1d90 » josh 2008-05-14 Prefer string core_ext infl... Comment 620
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 621 # A convenience wrapper for <tt>find(:first, *args)</tt>. You can pass in all the
622 # same arguments to this method as you can to <tt>find(:first)</tt>.
c6f2af5c » dhh 2008-03-24 Added ActiveRecord#Base.all... 623 def first(*args)
624 find(:first, *args)
625 end
73673256 » jeremy 2007-12-09 Document Active Record exce... 626
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 627 # A convenience wrapper for <tt>find(:last, *args)</tt>. You can pass in all the
628 # same arguments to this method as you can to <tt>find(:last)</tt>.
c6f2af5c » dhh 2008-03-24 Added ActiveRecord#Base.all... 629 def last(*args)
630 find(:last, *args)
631 end
3b0e1d90 » josh 2008-05-14 Prefer string core_ext infl... Comment 632
0a6980f2 » David Heinemeier Hansson 2008-04-28 Let Base.all use conditions... 633 # This is an alias for find(:all). You can pass in all the same arguments to this method as you can
634 # to find(:all)
635 def all(*args)
636 find(:all, *args)
637 end
3b0e1d90 » josh 2008-05-14 Prefer string core_ext infl... Comment 638
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 639 # Executes a custom SQL query against your database and returns all the results. The results will
73673256 » jeremy 2007-12-09 Document Active Record exce... 640 # be returned as an array with columns requested encapsulated as attributes of the model you call
a2932784 » lifo 2008-10-05 Merge docrails 641 # this method from. If you call <tt>Product.find_by_sql</tt> then the results will be returned in
642 # a Product object with the attributes you specified in the SQL query.
edf32cea » Marcel Molina 2007-12-05 More complete documentation... 643 #
73673256 » jeremy 2007-12-09 Document Active Record exce... 644 # If you call a complicated SQL query which spans multiple tables the columns specified by the
645 # SELECT will be attributes of the model, whether or not they are columns of the corresponding
edf32cea » Marcel Molina 2007-12-05 More complete documentation... 646 # table.
647 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 648 # The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be
73673256 » jeremy 2007-12-09 Document Active Record exce... 649 # no database agnostic conversions performed. This should be a last resort because using, for example,
650 # MySQL specific terms will lock you to using that particular database engine or require you to
a2932784 » lifo 2008-10-05 Merge docrails 651 # change your call if you switch engines.
edf32cea » Marcel Molina 2007-12-05 More complete documentation... 652 #
653 # ==== Examples
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 654 # # A simple SQL query spanning multiple tables
edf32cea » Marcel Molina 2007-12-05 More complete documentation... 655 # Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
656 # > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
657 #
658 # # You can use the same string replacement techniques as you can with ActiveRecord#find
659 # Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
660 # > [#<Post:0x36bff9c @attributes={"first_name"=>"The Cheap Man Buys Twice"}>, ...]
db045dbb » dhh 2004-11-23 Initial 661 def find_by_sql(sql)
6e3d2a79 » jeremy 2008-08-21 Revert "Performance: freeze... 662 connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) }
db045dbb » dhh 2004-11-23 Initial 663 end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 664
dbbae5e0 » lifo 2008-12-06 Merge with docrails 665 # Returns true if a record exists in the table that matches the +id+ or
5a8f7646 » smtlaissezfaire 2009-01-31 Add ActiveRecord::Base.exis... 666 # conditions given, or false otherwise. The argument can take five forms:
dbbae5e0 » lifo 2008-12-06 Merge with docrails 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>).
5a8f7646 » smtlaissezfaire 2009-01-31 Add ActiveRecord::Base.exis... 675 # * No args - Returns false if the table is empty, true otherwise.
971ed153 » Marcel Molina 2007-12-05 Document API for exists?'s ... 676 #
dbbae5e0 » lifo 2008-12-06 Merge with docrails 677 # For more information about specifying conditions as a Hash or Array,
678 # see the Conditions section in the introduction to ActiveRecord::Base.
971ed153 » Marcel Molina 2007-12-05 Document API for exists?'s ... 679 #
dbbae5e0 » lifo 2008-12-06 Merge with docrails 680 # Note: You can't pass in a condition as a string (like <tt>name =
681 # 'Jamie'</tt>), since it would be sanitized and then queried against
682 # the primary key column, like <tt>id = 'name = \'Jamie\''</tt>.
971ed153 » Marcel Molina 2007-12-05 Document API for exists?'s ... 683 #
684 # ==== Examples
abc895b8 » dhh 2005-04-03 Added new Base.find API and... 685 # Person.exists?(5)
58ebf302 » jeremy 2006-08-03 The exists? class method sh... 686 # Person.exists?('5')
8085cbfd » dhh 2006-08-03 Added support for condition... 687 # Person.exists?(:name => "David")
58ebf302 » jeremy 2006-08-03 The exists? class method sh... 688 # Person.exists?(['name LIKE ?', "%#{query}%"])
5a8f7646 » smtlaissezfaire 2009-01-31 Add ActiveRecord::Base.exis... 689 # Person.exists?
690 def exists?(id_or_conditions = {})
0ad24df6 » technoweenie 2008-01-02 Optimize ActiveRecord::Base... 691 connection.select_all(
692 construct_finder_sql(
3b0e1d90 » josh 2008-05-14 Prefer string core_ext infl... Comment 693 :select => "#{quoted_table_name}.#{primary_key}",
694 :conditions => expand_id_conditions(id_or_conditions),
0ad24df6 » technoweenie 2008-01-02 Optimize ActiveRecord::Base... 695 :limit => 1
3b0e1d90 » josh 2008-05-14 Prefer string core_ext infl... Comment 696 ),
0ad24df6 » technoweenie 2008-01-02 Optimize ActiveRecord::Base... 697 "#{name} Exists"
698 ).size > 0
db045dbb » dhh 2004-11-23 Initial 699 end
abc895b8 » dhh 2005-04-03 Added new Base.find API and... 700
73673256 » jeremy 2007-12-09 Document Active Record exce... 701 # Creates an object (or multiple objects) and saves it to the database, if validations pass.
a23bea7c » Marcel Molina 2007-12-05 Document API for create's a... 702 # The resulting object is returned whether the object was saved successfully to the database or not.
703 #
704 # The +attributes+ parameter can be either be a Hash or an Array of Hashes. These Hashes describe the
705 # attributes on the objects that are to be created.
706 #
707 # ==== Examples
708 # # Create a single new object
709 # User.create(:first_name => 'Jamie')
dd120ede » dhh 2008-04-30 Added block-setting of attr... 710 #
a23bea7c » Marcel Molina 2007-12-05 Document API for create's a... 711 # # Create an Array of new objects
dc4eec11 » lifo 2008-05-09 Merge docrails: 712 # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])
dd120ede » dhh 2008-04-30 Added block-setting of attr... 713 #
714 # # Create a single object and pass it into a block to set other attributes.
715 # User.create(:first_name => 'Jamie') do |u|
716 # u.is_admin = false
717 # end
718 #
719 # # Creating an Array of new objects using a block, where the block is executed for each object:
dc4eec11 » lifo 2008-05-09 Merge docrails: 720 # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u|
dd120ede » dhh 2008-04-30 Added block-setting of attr... 721 # u.is_admin = false
3b0e1d90 » josh 2008-05-14 Prefer string core_ext infl... Comment 722 # end
dd120ede » dhh 2008-04-30 Added block-setting of attr... 723 def create(attributes = nil, &block)
efa81dad » dhh 2005-01-25 Added the option of supplyi... 724 if attributes.is_a?(Array)
dd120ede » dhh 2008-04-30 Added block-setting of attr... 725 attributes.collect { |attr| create(attr, &block) }
efa81dad » dhh 2005-01-25 Added the option of supplyi... 726 else
727 object = new(attributes)
dd120ede » dhh 2008-04-30 Added block-setting of attr... 728 yield(object) if block_given?
efa81dad » dhh 2005-01-25 Added the option of supplyi... 729 object.save
730 object
731 end
db045dbb » dhh 2004-11-23 Initial 732 end
733
1b7a18de » Marcel Molina 2007-12-05 Document options and add ex... 734 # Updates an object (or multiple objects) and saves it to the database, if validations pass.
735 # The resulting object is returned whether the object was saved successfully to the database or not.
5e99422d » dhh 2006-02-25 Updated docs (closes #3799)... 736 #
a2932784 » lifo 2008-10-05 Merge docrails 737 # ==== Parameters
5e99422d » dhh 2006-02-25 Updated docs (closes #3799)... 738 #
dc4eec11 » lifo 2008-05-09 Merge docrails: 739 # * +id+ - This should be the id or an array of ids to be updated.
18eb80cc » lifo 2009-03-16 Merge docrails 740 # * +attributes+ - This should be a hash of attributes to be set on the object, or an array of hashes.
1b7a18de » Marcel Molina 2007-12-05 Document options and add ex... 741 #
742 # ==== Examples
743 #
744 # # Updating one record:
18eb80cc » lifo 2009-03-16 Merge docrails 745 # Person.update(15, :user_name => 'Samuel', :group => 'expert')
73673256 » jeremy 2007-12-09 Document Active Record exce... 746 #
1b7a18de » Marcel Molina 2007-12-05 Document options and add ex... 747 # # Updating multiple records:
dc4eec11 » lifo 2008-05-09 Merge docrails: 748 # people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
5e99422d » dhh 2006-02-25 Updated docs (closes #3799)... 749 # Person.update(people.keys, people.values)
db045dbb » dhh 2004-11-23 Initial 750 def update(id, attributes)
efa81dad » dhh 2005-01-25 Added the option of supplyi... 751 if id.is_a?(Array)
752 idx = -1
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 753 id.collect { |one_id| idx += 1; update(one_id, attributes[idx]) }
efa81dad » dhh 2005-01-25 Added the option of supplyi... 754 else
755 object = find(id)
756 object.update_attributes(attributes)
757 object
758 end
db045dbb » dhh 2004-11-23 Initial 759 end
760
39e1ac65 » lifo 2009-01-18 Merge docrails 761 # Deletes the row with a primary key matching the +id+ argument, using a
762 # SQL +DELETE+ statement, and returns the number of rows deleted. Active
763 # Record objects are not instantiated, so the object's callbacks are not
764 # executed, including any <tt>:dependent</tt> association options or
765 # Observer methods.
73673256 » jeremy 2007-12-09 Document Active Record exce... 766 #
39e1ac65 » lifo 2009-01-18 Merge docrails 767 # You can delete multiple rows at once by passing an Array of <tt>id</tt>s.
6a45e01b » Marcel Molina 2007-12-05 Document options and add ex... 768 #
39e1ac65 » lifo 2009-01-18 Merge docrails 769 # Note: Although it is often much faster than the alternative,
770 # <tt>#destroy</tt>, skipping callbacks might bypass business logic in
771 # your application that ensures referential integrity or performs other
772 # essential jobs.
6a45e01b » Marcel Molina 2007-12-05 Document options and add ex... 773 #
774 # ==== Examples
775 #
39e1ac65 » lifo 2009-01-18 Merge docrails 776 # # Delete a single row
6a45e01b » Marcel Molina 2007-12-05 Document options and add ex... 777 # Todo.delete(1)
73673256 » jeremy 2007-12-09 Document Active Record exce... 778 #
39e1ac65 » lifo 2009-01-18 Merge docrails 779 # # Delete multiple rows
780 # Todo.delete([2,3,4])
648b8fda » dhh 2004-12-17 Added Base.destroy and Base... 781 def delete(id)
98165fd3 » jeremy 2007-03-08 Consistently quote primary ... 782 delete_all([ "#{connection.quote_column_name(primary_key)} IN (?)", id ])
648b8fda » dhh 2004-12-17 Added Base.destroy and Base... 783 end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 784
ed69b38a » Marcel Molina 2007-12-05 Document options and add ex... 785 # Destroy an object (or multiple objects) that has the given id, the object is instantiated first,
786 # therefore all callbacks and filters are fired off before the object is deleted. This method is
787 # less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.
73673256 » jeremy 2007-12-09 Document Active Record exce... 788 #
789 # This essentially finds the object (or multiple objects) with the given id, creates a new object
ed69b38a » Marcel Molina 2007-12-05 Document options and add ex... 790 # from the attributes, and then calls destroy on it.
791 #
a2932784 » lifo 2008-10-05 Merge docrails 792 # ==== Parameters
73673256 » jeremy 2007-12-09 Document Active Record exce... 793 #
dc4eec11 » lifo 2008-05-09 Merge docrails: 794 # * +id+ - Can be either an Integer or an Array of Integers.
ed69b38a » Marcel Molina 2007-12-05 Document options and add ex... 795 #
796 # ==== Examples
797 #
798 # # Destroy a single object
799 # Todo.destroy(1)
73673256 » jeremy 2007-12-09 Document Active Record exce... 800 #
ed69b38a » Marcel Molina 2007-12-05 Document options and add ex... 801 # # Destroy multiple objects
802 # todos = [1,2,3]
803 # Todo.destroy(todos)
648b8fda » dhh 2004-12-17 Added Base.destroy and Base... 804 def destroy(id)
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 805 if id.is_a?(Array)
806 id.map { |one_id| destroy(one_id) }
807 else
808 find(id).destroy
809 end
648b8fda » dhh 2004-12-17 Added Base.destroy and Base... 810 end
811
4f1d353b » Marcel Molina 2007-12-05 Document options and add ex... 812 # Updates all records with details given if they match a set of conditions supplied, limits and order can
6ef35461 » lifo 2008-09-03 Merge docrails 813 # also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the
f97832b1 » lifo 2009-03-24 Merge docrails 814 # database. It does not instantiate the involved models and it does not trigger Active Record callbacks
815 # or validations.
a38f28ff » jeremy 2007-03-17 Base.update_all :order and ... 816 #
a2932784 » lifo 2008-10-05 Merge docrails 817 # ==== Parameters
4f1d353b » Marcel Molina 2007-12-05 Document options and add ex... 818 #
f97832b1 » lifo 2009-03-24 Merge docrails 819 # * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
820 # * +conditions+ - A string, array, or hash representing the WHERE part of an SQL statement. See conditions in the intro.
6ef35461 » lifo 2008-09-03 Merge docrails 821 # * +options+ - Additional options are <tt>:limit</tt> and <tt>:order</tt>, see the examples for usage.
4f1d353b » Marcel Molina 2007-12-05 Document options and add ex... 822 #
823 # ==== Examples
824 #
f97832b1 » lifo 2009-03-24 Merge docrails 825 # # Update all customers with the given attributes
826 # Customer.update_all :wants_email => true
73673256 » jeremy 2007-12-09 Document Active Record exce... 827 #
f97832b1 » lifo 2009-03-24 Merge docrails 828 # # Update all books with 'Rails' in their title
829 # Book.update_all "author = 'David'", "title LIKE '%Rails%'"
4f1d353b » Marcel Molina 2007-12-05 Document options and add ex... 830 #
f97832b1 » lifo 2009-03-24 Merge docrails 831 # # Update all avatars migrated more than a week ago
832 # Avatar.update_all ['migrated_at = ?, Time.now.utc], ['migrated_at > ?', 1.week.ago]
833 #
834 # # Update all books that match our conditions, but limit it to 5 ordered by date
835 # Book.update_all "author = 'David'", "title LIKE '%Rails%'", :order => 'created_at', :limit => 5
a38f28ff » jeremy 2007-03-17 Base.update_all :order and ... 836 def update_all(updates, conditions = nil, options = {})
ebe3a0d5 » jeremy 2008-01-05 More thoroughly quote table... 837 sql = "UPDATE #{quoted_table_name} SET #{sanitize_sql_for_assignment(updates)} "
7c9851db » tarmo 2008-09-10 Support :limit on update_al... 838
a38f28ff » jeremy 2007-03-17 Base.update_all :order and ... 839 scope = scope(:find)
7c9851db » tarmo 2008-09-10 Support :limit on update_al... 840
841 select_sql = ""
842 add_conditions!(select_sql, conditions, scope)
843
844 if options.has_key?(:limit) || (scope && scope[:limit])
845 # Only take order from scope if limit is also provided by scope, this
846 # is useful for updating a has_many association with a limit.
847 add_order!(select_sql, options[:order], scope)
848
849 add_limit!(select_sql, options, scope)
850 sql.concat(connection.limited_update_conditions(select_sql, quoted_table_name, connection.quote_column_name(primary_key)))
851 else
852 add_order!(select_sql, options[:order], nil)
853 sql.concat(select_sql)
854 end
855
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 856 connection.update(sql, "#{name} Update")
db045dbb » dhh 2004-11-23 Initial 857 end
0d2db8a7 » dhh 2005-01-24 Added Base.update_collectio... 858
39e1ac65 » lifo 2009-01-18 Merge docrails 859 # Destroys the records matching +conditions+ by instantiating each
860 # record and calling its +destroy+ method. Each object's callbacks are
861 # executed (including <tt>:dependent</tt> association options and
862 # +before_destroy+/+after_destroy+ Observer methods). Returns the
863 # collection of objects that were destroyed; each will be frozen, to
864 # reflect that no changes should be made (since they can't be
865 # persisted).
866 #
867 # Note: Instantiation, callback execution, and deletion of each
868 # record can be time consuming when you're removing many records at
869 # once. It generates at least one SQL +DELETE+ query per record (or
870 # possibly more, to enforce your callbacks). If you want to delete many
871 # rows quickly, without concern for their associations or callbacks, use
872 # +delete_all+ instead.
4b055a4a » jeremy 2007-12-10 Update destroy_all and dele... 873 #
a2932784 » lifo 2008-10-05 Merge docrails 874 # ==== Parameters
4b055a4a » jeremy 2007-12-10 Update destroy_all and dele... 875 #
39e1ac65 » lifo 2009-01-18 Merge docrails 876 # * +conditions+ - A string, array, or hash that specifies which records
877 # to destroy. If omitted, all records are destroyed. See the
878 # Conditions section in the introduction to ActiveRecord::Base for
879 # more information.
4b055a4a » jeremy 2007-12-10 Update destroy_all and dele... 880 #
39e1ac65 » lifo 2009-01-18 Merge docrails 881 # ==== Examples
4b055a4a » jeremy 2007-12-10 Update destroy_all and dele... 882 #
a2932784 » lifo 2008-10-05 Merge docrails 883 # Person.destroy_all("last_login < '2004-04-04'")
39e1ac65 » lifo 2009-01-18 Merge docrails 884 # Person.destroy_all(:status => "inactive")
db045dbb » dhh 2004-11-23 Initial 885 def destroy_all(conditions = nil)
3dfa56cc » dhh 2005-06-26 Updated all references to t... 886 find(:all, :conditions => conditions).each { |object| object.destroy }
db045dbb » dhh 2004-11-23 Initial 887 end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 888
4b055a4a » jeremy 2007-12-10 Update destroy_all and dele... 889 # Deletes the records matching +conditions+ without instantiating the records first, and hence not
6ef35461 » lifo 2008-09-03 Merge docrails 890 # calling the +destroy+ method nor invoking callbacks. This is a single SQL DELETE statement that
a2932784 » lifo 2008-10-05 Merge docrails 891 # goes straight to the database, much more efficient than +destroy_all+. Be careful with relations
53cd102b » lifo 2009-02-24 Merge with docrails 892 # though, in particular <tt>:dependent</tt> rules defined on associations are not honored. Returns
893 # the number of rows affected.
4b055a4a » jeremy 2007-12-10 Update destroy_all and dele... 894 #
a2932784 » lifo 2008-10-05 Merge docrails 895 # ==== Parameters
4b055a4a » jeremy 2007-12-10 Update destroy_all and dele... 896 #
dc4eec11 » lifo 2008-05-09 Merge docrails: 897 # * +conditions+ - Conditions are specified the same way as with +find+ method.
4b055a4a » jeremy 2007-12-10 Update destroy_all and dele... 898 #
899 # ==== Example
900 #
a2932784 » lifo 2008-10-05 Merge docrails 901 # Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
902 # Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
4b055a4a » jeremy 2007-12-10 Update destroy_all and dele... 903 #
a2932784 » lifo 2008-10-05 Merge docrails 904 # Both calls delete the affected posts all at once with a single DELETE statement. If you need to destroy dependent
6ef35461 » lifo 2008-09-03 Merge docrails 905 # associations or call your <tt>before_*</tt> or +after_destroy+ callbacks, use the +destroy_all+ method instead.
db045dbb » dhh 2004-11-23 Initial 906 def delete_all(conditions = nil)
9b6207c3 » jeremy 2007-10-15 Quote table names. Defaults... 907 sql = "DELETE FROM #{quoted_table_name} "
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 908 add_conditions!(sql, conditions, scope(:find))
db045dbb » dhh 2004-11-23 Initial 909 connection.delete(sql, "#{name} Delete all")
910 end
911
912 # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
73673256 » jeremy 2007-12-09 Document Active Record exce... 913 # The use of this method should be restricted to complicated SQL queries that can't be executed
ee614d63 » Marcel Molina 2007-05-05 Add documentation caveat ab... 914 # using the ActiveRecord::Calculations class methods. Look into those before using this.
915 #
a2932784 » lifo 2008-10-05 Merge docrails 916 # ==== Parameters
73673256 » jeremy 2007-12-09 Document Active Record exce... 917 #
dc4eec11 » lifo 2008-05-09 Merge docrails: 918 # * +sql+ - An SQL statement which should return a count query from the database, see the example below.
ee614d63 » Marcel Molina 2007-05-05 Add documentation caveat ab... 919 #
920 # ==== Examples
921 #
e17bf818 » jamis 2005-08-14 Fix typo in count_by_sql do... 922 # Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
db045dbb » dhh 2004-11-23 Initial 923 def count_by_sql(sql)
a775cb19 » dhh 2004-12-07 Added the option for saniti... 924 sql = sanitize_conditions(sql)
caaf40d5 » dhh 2005-09-24 Added AbstractAdapter#selec... 925 connection.select_value(sql, "#{name} Count").to_i
db045dbb » dhh 2004-11-23 Initial 926 end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 927
83752373 » jamis 2007-02-07 Made increment_counter/decr... 928 # A generic "counter updater" implementation, intended primarily to be
929 # used by increment_counter and decrement_counter, but which may also
930 # be useful on its own. It simply does a direct SQL update for the record
931 # with the given ID, altering the given hash of counters by the amount
932 # given by the corresponding value:
933 #
a2932784 » lifo 2008-10-05 Merge docrails 934 # ==== Parameters
73673256 » jeremy 2007-12-09 Document Active Record exce... 935 #
74871961 » lifo 2009-01-28 Add array id support to Mod... 936 # * +id+ - The id of the object you wish to update a counter on or an Array of ids.
dc4eec11 » lifo 2008-05-09 Merge docrails: 937 # * +counters+ - An Array of Hashes containing the names of the fields
938 # to update as keys and the amount to update the field by as values.
73673256 » jeremy 2007-12-09 Document Active Record exce... 939 #
6bd7d30e » Marcel Molina 2007-12-05 Document options for update... 940 # ==== Examples
73673256 » jeremy 2007-12-09 Document Active Record exce... 941 #
942 # # For the Post with id of 5, decrement the comment_count by 1, and
6bd7d30e » Marcel Molina 2007-12-05 Document options for update... 943 # # increment the action_count by 1
83752373 » jamis 2007-02-07 Made increment_counter/decr... 944 # Post.update_counters 5, :comment_count => -1, :action_count => 1
6bd7d30e » Marcel Molina 2007-12-05 Document options for update... 945 # # Executes the following SQL:
83752373 » jamis 2007-02-07 Made increment_counter/decr... 946 # # UPDATE posts
947 # # SET comment_count = comment_count - 1,
948 # # action_count = action_count + 1
949 # # WHERE id = 5
74871961 » lifo 2009-01-28 Add array id support to Mod... 950 #
951 # # For the Posts with id of 10 and 15, increment the comment_count by 1
952 # Post.update_counters [10, 15], :comment_count => 1
953 # # Executes the following SQL:
954 # # UPDATE posts
955 # # SET comment_count = comment_count + 1,
956 # # WHERE id IN (10, 15)
83752373 » jamis 2007-02-07 Made increment_counter/decr... 957 def update_counters(id, counters)
958 updates = counters.inject([]) { |list, (counter_name, increment)|
959 sign = increment < 0 ? "-" : "+"
459e5817 » miloops 2008-06-26 update_counters should upda... 960 list << "#{connection.quote_column_name(counter_name)} = COALESCE(#{connection.quote_column_name(counter_name)}, 0) #{sign} #{increment.abs}"
83752373 » jamis 2007-02-07 Made increment_counter/decr... 961 }.join(", ")
74871961 » lifo 2009-01-28 Add array id support to Mod... 962
963 if id.is_a?(Array)
964 ids_list = id.map {|i| quote_value(i)}.join(', ')
965 condition = "IN (#{ids_list})"
966 else
967 condition = "= #{quote_value(id)}"
968 end
969
970 update_all(updates, "#{connection.quote_column_name(primary_key)} #{condition}")
83752373 » jamis 2007-02-07 Made increment_counter/decr... 971 end
972
15dc567e » Marcel Molina 2007-05-05 Also add documentation enha... 973 # Increment a number field by one, usually representing a count.
974 #
73673256 » jeremy 2007-12-09 Document Active Record exce... 975 # This is used for caching aggregate values, so that they don't need to be computed every time.
976 # For example, a DiscussionBoard may cache post_count and comment_count otherwise every time the board is
7143d801 » Marcel Molina 2007-11-07 Smattering of grammatical f... 977 # shown it would have to run an SQL query to find how many posts and comments there are.
15dc567e » Marcel Molina 2007-05-05 Also add documentation enha... 978 #
a2932784 » lifo 2008-10-05 Merge docrails 979 # ==== Parameters
15dc567e » Marcel Molina 2007-05-05 Also add documentation enha... 980 #
dc4eec11 » lifo 2008-05-09 Merge docrails: 981 # * +counter_name+ - The name of the field that should be incremented.
982 # * +id+ - The id of the object that should be incremented.
15dc567e » Marcel Molina 2007-05-05 Also add documentation enha... 983 #
984 # ==== Examples
985 #
986 # # Increment the post_count column for the record with an id of 5
987 # DiscussionBoard.increment_counter(:post_count, 5)
db045dbb » dhh 2004-11-23 Initial 988 def increment_counter(counter_name, id)
83752373 » jamis 2007-02-07 Made increment_counter/decr... 989 update_counters(id, counter_name => 1)
db045dbb » dhh 2004-11-23 Initial 990 end
991
5bd35705 » Marcel Molina 2007-05-05 Enhance documentation for d... 992 # Decrement a number field by one, usually representing a count.
993 #
994 # This works the same as increment_counter but reduces the column value by 1 instead of increasing it.
995 #
a2932784 » lifo 2008-10-05 Merge docrails 996 # ==== Parameters
5bd35705 » Marcel Molina 2007-05-05 Enhance documentation for d... 997 #
dc4eec11 » lifo 2008-05-09 Merge docrails: 998 # * +counter_name+ - The name of the field that should be decremented.
999 # * +id+ - The id of the object that should be decremented.
5bd35705 » Marcel Molina 2007-05-05 Enhance documentation for d... 1000 #
1001 # ==== Examples
1002 #
1003 # # Decrement the post_count column for the record with an id of 5
1004 # DiscussionBoard.decrement_counter(:post_count, 5)
db045dbb » dhh 2004-11-23 Initial 1005 def decrement_counter(counter_name, id)
83752373 » jamis 2007-02-07 Made increment_counter/decr... 1006 update_counters(id, counter_name => -1)
db045dbb » dhh 2004-11-23 Initial 1007 end
1008
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 1009 # Attributes named in this macro are protected from mass-assignment,
1010 # such as <tt>new(attributes)</tt>,
1011 # <tt>update_attributes(attributes)</tt>, or
1012 # <tt>attributes=(attributes)</tt>.
1013 #
1014 # Mass-assignment to these attributes will simply be ignored, to assign
1015 # to them you can use direct writer methods. This is meant to protect
1016 # sensitive attributes from being overwritten by malicious users
1017 # tampering with URLs or forms.
db045dbb » dhh 2004-11-23 Initial 1018 #
1019 # class Customer < ActiveRecord::Base
1020 # attr_protected :credit_rating
1021 # end
1022 #
1023 # customer = Customer.new("name" => David, "credit_rating" => "Excellent")
1024 # customer.credit_rating # => nil
1025 # customer.attributes = { "description" => "Jolly fellow", "credit_rating" => "Superb" }
1026 # customer.credit_rating # => nil
1027 #
1028 # customer.credit_rating = "Average"
1029 # customer.credit_rating # => "Average"
d761ac40 » Marcel Molina 2007-10-25 Add docs explaining how to ... 1030 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 1031 # To start from an all-closed default and enable attributes as needed,
1032 # have a look at +attr_accessible+.
db045dbb » dhh 2004-11-23 Initial 1033 def attr_protected(*attributes)
288e947a » clemens 2008-09-02 Some performance goodness f... 1034 write_inheritable_attribute(:attr_protected, Set.new(attributes.map(&:to_s)) + (protected_attributes || []))
db045dbb » dhh 2004-11-23 Initial 1035 end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 1036
098fa943 » dhh 2005-02-07 Fixed documentation snafus ... 1037 # Returns an array of all the attributes that have been protected from mass-assignment.
db045dbb » dhh 2004-11-23 Initial 1038 def protected_attributes # :nodoc:
288e947a » clemens 2008-09-02 Some performance goodness f... 1039 read_inheritable_attribute(:attr_protected)
db045dbb » dhh 2004-11-23 Initial 1040 end
1041
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 1042 # Specifies a white list of model attributes that can be set via
1043 # mass-assignment, such as <tt>new(attributes)</tt>,
1044 # <tt>update_attributes(attributes)</tt>, or
1045 # <tt>attributes=(attributes)</tt>
f770b829 » Marcel Molina 2007-11-06 Enhance explanation with mo... 1046 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 1047 # This is the opposite of the +attr_protected+ macro: Mass-assignment
1048 # will only set attributes in this list, to assign to the rest of
1049 # attributes you can use direct writer methods. This is meant to protect
1050 # sensitive attributes from being overwritten by malicious users
1051 # tampering with URLs or forms. If you'd rather start from an all-open
1052 # default and restrict attributes as needed, have a look at
1053 # +attr_protected+.
d761ac40 » Marcel Molina 2007-10-25 Add docs explaining how to ... 1054 #
1055 # class Customer < ActiveRecord::Base
f770b829 » Marcel Molina 2007-11-06 Enhance explanation with mo... 1056 # attr_accessible :name, :nickname
d761ac40 » Marcel Molina 2007-10-25 Add docs explaining how to ... 1057 # end
1058 #
f770b829 » Marcel Molina 2007-11-06 Enhance explanation with mo... 1059 # customer = Customer.new(:name => "David", :nickname => "Dave", :credit_rating => "Excellent")
1060 # customer.credit_rating # => nil
1061 # customer.attributes = { :name => "Jolly fellow", :credit_rating => "Superb" }
1062 # customer.credit_rating # => nil
d761ac40 » Marcel Molina 2007-10-25 Add docs explaining how to ... 1063 #
f770b829 » Marcel Molina 2007-11-06 Enhance explanation with mo... 1064 # customer.credit_rating = "Average"
1065 # customer.credit_rating # => "Average"
db045dbb » dhh 2004-11-23 Initial 1066 def attr_accessible(*attributes)
288e947a » clemens 2008-09-02 Some performance goodness f... 1067 write_inheritable_attribute(:attr_accessible, Set.new(attributes.map(&:to_s)) + (accessible_attributes || []))
db045dbb » dhh 2004-11-23 Initial 1068 end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 1069
098fa943 » dhh 2005-02-07 Fixed documentation snafus ... 1070 # Returns an array of all the attributes that have been made accessible to mass-assignment.
db045dbb » dhh 2004-11-23 Initial 1071 def accessible_attributes # :nodoc:
288e947a » clemens 2008-09-02 Some performance goodness f... 1072 read_inheritable_attribute(:attr_accessible)
db045dbb » dhh 2004-11-23 Initial 1073 end
1074
66d05f5e » technoweenie 2007-09-30 Add attr_readonly to specif... 1075 # Attributes listed as readonly can be set for a new record, but will be ignored in database updates afterwards.
1076 def attr_readonly(*attributes)
288e947a » clemens 2008-09-02 Some performance goodness f... 1077 write_inheritable_attribute(:attr_readonly, Set.new(attributes.map(&:to_s)) + (readonly_attributes || []))
66d05f5e » technoweenie 2007-09-30 Add attr_readonly to specif... 1078 end
1079
1080 # Returns an array of all the attributes that have been specified as readonly.
1081 def readonly_attributes
288e947a » clemens 2008-09-02 Some performance goodness f... 1082 read_inheritable_attribute(:attr_readonly)
66d05f5e » technoweenie 2007-09-30 Add attr_readonly to specif... 1083 end
c450a36f » dhh 2006-03-05 Doc fixes 1084
73673256 » jeremy 2007-12-09 Document Active Record exce... 1085 # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object,
1086 # then specify the name of that attribute using this method and it will be handled automatically.
1087 # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 1088 # class on retrieval or SerializationTypeMismatch will be raised.
1a0cdf74 » dhh 2007-06-23 Docfix (closes #8096) 1089 #
a2932784 » lifo 2008-10-05 Merge docrails 1090 # ==== Parameters
1a0cdf74 » dhh 2007-06-23 Docfix (closes #8096) 1091 #
dc4eec11 » lifo 2008-05-09 Merge docrails: 1092 # * +attr_name+ - The field name that should be serialized.
1093 # * +class_name+ - Optional, class name that the object type should be equal to.
1a0cdf74 » dhh 2007-06-23 Docfix (closes #8096) 1094 #
1095 # ==== Example
1096 # # Serialize a preferences attribute
1097 # class User
1098 # serialize :preferences
1099 # end
db045dbb » dhh 2004-11-23 Initial 1100 def serialize(attr_name, class_name = Object)
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 1101 serialized_attributes[attr_name.to_s] = class_name
db045dbb » dhh 2004-11-23 Initial 1102 end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 1103
db045dbb » dhh 2004-11-23 Initial 1104 # Returns a hash of all the attributes that have been specified for serialization as keys and their class restriction as values.
1105 def serialized_attributes
288e947a » clemens 2008-09-02 Some performance goodness f... 1106 read_inheritable_attribute(:attr_serialized) or write_inheritable_attribute(:attr_serialized, {})
db045dbb » dhh 2004-11-23 Initial 1107 end
1108
1109 # Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 1110 # directly from ActiveRecord::Base. So if the hierarchy looks like: Reply < Message < ActiveRecord::Base, then Message is used
d64832c0 » Marcel Molina 2007-12-05 Give examples for what tabl... 1111 # to guess the table name even when called on Reply. The rules used to do the guess are handled by the Inflector class
7143d801 » Marcel Molina 2007-11-07 Smattering of grammatical f... 1112 # in Active Support, which knows almost all common English inflections. You can add new inflections in config/initializers/inflections.rb.
db045dbb » dhh 2004-11-23 Initial 1113 #
14101c7b » jeremy 2006-08-16 Nested classes are given ta... 1114 # Nested classes are given table names prefixed by the singular form of
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 1115 # the parent's table name. Enclosing modules are not considered.
1116 #
1117 # ==== Examples
d64832c0 » Marcel Molina 2007-12-05 Give examples for what tabl... 1118 #
1119 # class Invoice < ActiveRecord::Base; end;
14101c7b » jeremy 2006-08-16 Nested classes are given ta... 1120 # file class table_name
1121 # invoice.rb Invoice invoices
d64832c0 » Marcel Molina 2007-12-05 Give examples for what tabl... 1122 #
1123 # class Invoice < ActiveRecord::Base; class Lineitem < ActiveRecord::Base; end; end;
1124 # file class table_name
1125 # invoice.rb Invoice::Lineitem invoice_lineitems
1126 #
1127 # module Invoice; class Lineitem < ActiveRecord::Base; end; end;
1128 # file class table_name
1129 # invoice/lineitem.rb Invoice::Lineitem lineitems
db045dbb » dhh 2004-11-23 Initial 1130 #
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 1131 # Additionally, the class-level +table_name_prefix+ is prepended and the
1132 # +table_name_suffix+ is appended. So if you have "myapp_" as a prefix,
14101c7b » jeremy 2006-08-16 Nested classes are given ta... 1133 # the table name guess for an Invoice class becomes "myapp_invoices".
1134 # Invoice::Lineitem becomes "myapp_invoice_lineitems".
1135 #
1136 # You can also overwrite this class method to allow for unguessable
1137 # links, such as a Mouse class with a link to a "mice" table. Example:
db045dbb » dhh 2004-11-23 Initial 1138 #
1139 # class Mouse < ActiveRecord::Base
14101c7b » jeremy 2006-08-16 Nested classes are given ta... 1140 # set_table_name "mice"
db045dbb » dhh 2004-11-23 Initial 1141 # end
dcc48680 » dhh 2004-12-22 Fixed that Base.table_name ... 1142 def table_name
d736568f » Marcel Molina 2005-10-10 Speed up the setting of tab... 1143 reset_table_name
1144 end
1145
fed7d334 » dhh 2006-03-27 Fixed documentation 1146 def reset_table_name #:nodoc:
bcbce90b » jeremy 2006-08-25 Nested subclasses are not p... 1147 base = base_class
1148
1149 name =
1150 # STI subclasses always use their superclass' table.
1151 unless self == base
1152 base.table_name
1153 else
1154 # Nested classes are prefixed with singular parent table name.
1155 if parent < ActiveRecord::Base && !parent.abstract_class?
1156 contained = parent.table_name
1157 contained = contained.singularize if parent.pluralize_table_names
1158 contained << '_'
1159 end
1160 name = "#{table_name_prefix}#{contained}#{undecorated_table_name(base.name)}#{table_name_suffix}"
1161 end
1162
c450a36f » dhh 2006-03-05 Doc fixes 1163 set_table_name(name)
d736568f » Marcel Molina 2005-10-10 Speed up the setting of tab... 1164 name
db045dbb » dhh 2004-11-23 Initial 1165 end
1166
098fa943 » dhh 2005-02-07 Fixed documentation snafus ... 1167 # Defines the primary key field -- can be overridden in subclasses. Overwriting will negate any effect of the
db045dbb » dhh 2004-11-23 Initial 1168 # primary_key_prefix_type setting, though.
1169 def primary_key
c0899bca » Marcel Molina 2005-10-06 Add convenience predicate m... 1170 reset_primary_key
1171 end
1172
fed7d334 » dhh 2006-03-27 Fixed documentation 1173 def reset_primary_key #:nodoc:
dfa68883 » jeremy 2008-03-18 Migrations: create_table su... 1174 key = get_primary_key(base_class.name)
1175 set_primary_key(key)
1176 key
1177 end
1178
1179 def get_primary_key(base_name) #:nodoc:
c0899bca » Marcel Molina 2005-10-06 Add convenience predicate m... 1180 key = 'id'
db045dbb » dhh 2004-11-23 Initial 1181 case primary_key_prefix_type
1182 when :table_name
3b0e1d90 » josh 2008-05-14 Prefer string core_ext infl... Comment 1183 key = base_name.to_s.foreign_key(false)
db045dbb » dhh 2004-11-23 Initial 1184 when :table_name_with_underscore
3b0e1d90 » josh 2008-05-14 Prefer string core_ext infl... Comment 1185 key = base_name.to_s.foreign_key
db045dbb » dhh 2004-11-23 Initial 1186 end
c0899bca » Marcel Molina 2005-10-06 Add convenience predicate m... 1187 key
db045dbb » dhh 2004-11-23 Initial 1188 end
1189
9d2da046 » jeremy 2006-11-09 Cache inheritance_column. C... 1190 # Defines the column name for use with single table inheritance
1191 # -- can be set in subclasses like so: self.inheritance_column = "type_id"
db045dbb » dhh 2004-11-23 Initial 1192 def inheritance_column
9d2da046 » jeremy 2006-11-09 Cache inheritance_column. C... 1193 @inheritance_column ||= "type".freeze
db045dbb » dhh 2004-11-23 Initial 1194 end
1195
7c8f3edc » jeremy 2005-11-12 r4325@asus: jeremy | 2005... 1196 # Lazy-set the sequence name to the connection's default. This method
1197 # is only ever called once since set_sequence_name overrides it.
fed7d334 » dhh 2006-03-27 Fixed documentation 1198 def sequence_name #:nodoc:
7c8f3edc » jeremy 2005-11-12 r4325@asus: jeremy | 2005... 1199 reset_sequence_name
1200 end
1201
fed7d334 » dhh 2006-03-27 Fixed documentation 1202 def reset_sequence_name #:nodoc:
7c8f3edc » jeremy 2005-11-12 r4325@asus: jeremy | 2005... 1203 default = connection.default_sequence_name(table_name, primary_key)
1204 set_sequence_name(default)
1205 default
14ea3128 » dhh 2005-07-24 Made Oracle a first-class c... 1206 end
1207
1aa82b32 » dhh 2005-02-07 Added keyword-style approac... 1208 # Sets the table name to use to the given value, or (if the value
4eab3758 » dhh 2005-02-23 Finished polishing API docs 1209 # is nil or false) to the value returned by the given block.
1aa82b32 » dhh 2005-02-07 Added keyword-style approac... 1210 #
1211 # class Project < ActiveRecord::Base
1212 # set_table_name "project"
1213 # end
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1214 def set_table_name(value = nil, &block)
1aa82b32 » dhh 2005-02-07 Added keyword-style approac... 1215 define_attr_method :table_name, value, &block
1216 end
1217 alias :table_name= :set_table_name
1218
1219 # Sets the name of the primary key column to use to the given value,
1220 # or (if the value is nil or false) to the value returned by the given
4eab3758 » dhh 2005-02-23 Finished polishing API docs 1221 # block.
1aa82b32 » dhh 2005-02-07 Added keyword-style approac... 1222 #
1223 # class Project < ActiveRecord::Base
1224 # set_primary_key "sysid"
1225 # end
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1226 def set_primary_key(value = nil, &block)
1aa82b32 » dhh 2005-02-07 Added keyword-style approac... 1227 define_attr_method :primary_key, value, &block
1228 end
1229 alias :primary_key= :set_primary_key
1230
1231 # Sets the name of the inheritance column to use to the given value,
1232 # or (if the value # is nil or false) to the value returned by the
4eab3758 » dhh 2005-02-23 Finished polishing API docs 1233 # given block.
1aa82b32 » dhh 2005-02-07 Added keyword-style approac... 1234 #
1235 # class Project < ActiveRecord::Base
1236 # set_inheritance_column do
1237 # original_inheritance_column + "_id"
1238 # end
1239 # end
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1240 def set_inheritance_column(value = nil, &block)
1aa82b32 » dhh 2005-02-07 Added keyword-style approac... 1241 define_attr_method :inheritance_column, value, &block
1242 end
1243 alias :inheritance_column= :set_inheritance_column
1244
14ea3128 » dhh 2005-07-24 Made Oracle a first-class c... 1245 # Sets the name of the sequence to use when generating ids to the given
1246 # value, or (if the value is nil or false) to the value returned by the
7117fdb8 » jeremy 2005-10-15 r3616@asus: jeremy | 2005... 1247 # given block. This is required for Oracle and is useful for any
1248 # database which relies on sequences for primary key generation.
14ea3128 » dhh 2005-07-24 Made Oracle a first-class c... 1249 #
2076dca6 » jeremy 2005-11-16 r3095@asus: jeremy | 2005... 1250 # If a sequence name is not explicitly set when using Oracle or Firebird,
1251 # it will default to the commonly used pattern of: #{table_name}_seq
1252 #
1253 # If a sequence name is not explicitly set when using PostgreSQL, it
1254 # will discover the sequence corresponding to your primary key for you.
14ea3128 » dhh 2005-07-24 Made Oracle a first-class c... 1255 #
1256 # class Project < ActiveRecord::Base
1257 # set_sequence_name "projectseq" # default would have been "project_seq"
1258 # end
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1259 def set_sequence_name(value = nil, &block)
14ea3128 » dhh 2005-07-24 Made Oracle a first-class c... 1260 define_attr_method :sequence_name, value, &block
1261 end
1262 alias :sequence_name= :set_sequence_name
1263
db045dbb » dhh 2004-11-23 Initial 1264 # Turns the +table_name+ back into a class name following the reverse rules of +table_name+.
1265 def class_name(table_name = table_name) # :nodoc:
1266 # remove any prefix and/or suffix from the table name
81737fc0 » jeremy 2005-07-03 r1613@asus: jeremy | 2005... 1267 class_name = table_name[table_name_prefix.length..-(table_name_suffix.length + 1)].camelize
1268 class_name = class_name.singularize if pluralize_table_names
1269 class_name
db045dbb » dhh 2004-11-23 Initial 1270 end
1271
816f37a2 » dhh 2005-10-28 Added migration support to ... 1272 # Indicates whether the table associated with this class exists
1273 def table_exists?
8877ab58 » tarmo 2008-05-06 Added AbstractAdapter#table... 1274 connection.table_exists?(table_name)
816f37a2 » dhh 2005-10-28 Added migration support to ... 1275 end
1276
db045dbb » dhh 2004-11-23 Initial 1277 # Returns an array of column objects for the table associated with this class.
1278 def columns
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1279 unless defined?(@columns) && @columns
c0899bca » Marcel Molina 2005-10-06 Add convenience predicate m... 1280 @columns = connection.columns(table_name, "#{name} Columns")
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1281 @columns.each { |column| column.primary = column.name == primary_key }
c0899bca » Marcel Molina 2005-10-06 Add convenience predicate m... 1282 end
1283 @columns
db045dbb » dhh 2004-11-23 Initial 1284 end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 1285
3b4450bb » NZKoz 2006-12-27 Docs fix for columns_hash [... 1286 # Returns a hash of column objects for the table associated with this class.
db045dbb » dhh 2004-11-23 Initial 1287 def columns_hash
1288 @columns_hash ||= columns.inject({}) { |hash, column| hash[column.name] = column; hash }
1289 end
d0bd3b5a » jeremy 2005-06-11 Return PostgreSQL columns i... 1290
fed7d334 » dhh 2006-03-27 Fixed documentation 1291 # Returns an array of column names as strings.
49d0f0cb » dhh 2005-04-18 Speeded up eager loading a ... 1292 def column_names
d0bd3b5a » jeremy 2005-06-11 Return PostgreSQL columns i... 1293 @column_names ||= columns.map { |column| column.name }
49d0f0cb » dhh 2005-04-18 Speeded up eager loading a ... 1294 end
db045dbb » dhh 2004-11-23 Initial 1295
2948910b » Marcel Molina 2005-10-10 Misc doc fixes (typos/gramm... 1296 # Returns an array of column objects where the primary id, all columns ending in "_id" or "_count",
1297 # and columns used for single table inheritance have been removed.
db045dbb » dhh 2004-11-23 Initial 1298 def content_columns
c0899bca » Marcel Molina 2005-10-06 Add convenience predicate m... 1299 @content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column }
db045dbb » dhh 2004-11-23 Initial 1300 end
1301
1302 # Returns a hash of all the methods added to query each of the columns in the table with the name of the method as the key
1303 # and true as the value. This makes it possible to do O(1) lookups in respond_to? to check if a given method for attribute
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 1304 # is available.
fed7d334 » dhh 2006-03-27 Fixed documentation 1305 def column_methods_hash #:nodoc:
d0bd3b5a » jeremy 2005-06-11 Return PostgreSQL columns i... 1306 @dynamic_methods_hash ||= column_names.inject(Hash.new(false)) do |methods, attr|
3ab3a70b » jeremy 2005-10-22 Clarify semantics of Active... 1307 attr_name = attr.to_s
1308 methods[attr.to_sym] = attr_name
1309 methods["#{attr}=".to_sym] = attr_name
1310 methods["#{attr}?".to_sym] = attr_name
1311 methods["#{attr}_before_type_cast".to_sym] = attr_name
db045dbb » dhh 2004-11-23 Initial 1312 methods
1313 end
1314 end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 1315
a2932784 » lifo 2008-10-05 Merge docrails 1316 # Resets all the cached information about columns, which will cause them
1317 # to be reloaded on the next request.
1318 #
1319 # The most common usage pattern for this method is probably in a migration,
1320 # when just after creating a table you want to populate it with some default
1321 # values, eg:
1322 #
1323 # class CreateJobLevels < ActiveRecord::Migration
1324 # def self.up
1325 # create_table :job_levels do |t|
1326 # t.integer :id
1327 # t.string :name
1328 #
1329 # t.timestamps
1330 # end
1331 #
1332 # JobLevel.reset_column_information
1333 # %w{assistant executive manager director}.each do |type|
1334 # JobLevel.create(:name => type)
1335 # end
1336 # end
1337 #
1338 # def self.down
1339 # drop_table :job_levels
1340 # end
1341 # end
1314f48d » dhh 2004-12-12 Added methods for resetting... 1342 def reset_column_information
5b801b59 » NZKoz 2007-08-14 Change the implementation o... 1343 generated_methods.each { |name| undef_method(name) }
1344 @column_names = @columns = @columns_hash = @content_columns = @dynamic_methods_hash = @generated_methods = @inheritance_column = nil
1314f48d » dhh 2004-12-12 Added methods for resetting... 1345 end
1346
4eab3758 » dhh 2005-02-23 Finished polishing API docs 1347 def reset_column_information_and_inheritable_attributes_for_all_subclasses#:nodoc:
1314f48d » dhh 2004-12-12 Added methods for resetting... 1348 subclasses.each { |klass| klass.reset_inheritable_attributes; klass.reset_column_information }
1349 end
db045dbb » dhh 2004-11-23 Initial 1350
3c64c9a5 » chrisk 2009-03-12 Fix spelling of an internal... 1351 def self_and_descendants_from_active_record#nodoc:
ffeab4e0 » iain 2008-08-13 Cleaned up ActiveRecord i18... 1352 klass = self
1353 classes = [klass]
1354 while klass != klass.base_class
1355 classes << klass = klass.superclass
1356 end
1357 classes
1358 rescue
1359 # OPTIMIZE this rescue is to fix this test: ./test/cases/reflection_test.rb:56:in `test_human_name_for_column'
1360 # Appearantly the method base_class causes some trouble.
1361 # It now works for sure.
1362 [self]
1363 end
1364
db045dbb » dhh 2004-11-23 Initial 1365 # Transforms attribute key names into a more humane format, such as "First name" instead of "first_name". Example:
1366 # Person.human_attribute_name("first_name") # => "First name"
ffeab4e0 » iain 2008-08-13 Cleaned up ActiveRecord i18... 1367 # This used to be depricated in favor of humanize, but is now preferred, because it automatically uses the I18n
1368 # module now.
1369 # Specify +options+ with additional translating options.
1370 def human_attribute_name(attribute_key_name, options = {})
3c64c9a5 » chrisk 2009-03-12 Fix spelling of an internal... 1371 defaults = self_and_descendants_from_active_record.map do |klass|
ffeab4e0 » iain 2008-08-13 Cleaned up ActiveRecord i18... 1372 :"#{klass.name.underscore}.#{attribute_key_name}"
1373 end
1374 defaults << options[:default] if options[:default]
1375 defaults.flatten!
1376 defaults << attribute_key_name.humanize
1377 options[:count] ||= 1
1378 I18n.translate(defaults.shift, options.merge(:default => defaults, :scope => [:activerecord, :attributes]))
db045dbb » dhh 2004-11-23 Initial 1379 end
81e14fad » iain 2008-08-16 Added Base.human_name method 1380
1381 # Transform the modelname into a more humane format, using I18n.
1382 # Defaults to the basic humanize method.
1383 # Default scope of the translation is activerecord.models
1384 # Specify +options+ with additional translating options.
1385 def human_name(options = {})
3c64c9a5 » chrisk 2009-03-12 Fix spelling of an internal... 1386 defaults = self_and_descendants_from_active_record.map do |klass|
81e14fad » iain 2008-08-16 Added Base.human_name method 1387 :"#{klass.name.underscore}"
1388 end
1389 defaults << self.name.humanize
1390 I18n.translate(defaults.shift, {:scope => [:activerecord, :models], :count => 1, :default => defaults}.merge(options))
db045dbb » dhh 2004-11-23 Initial 1391 end
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 1392
06afb8c7 » jeremy 2007-01-22 Subclasses of an abstract c... 1393 # True if this isn't a concrete subclass needing a STI type condition.
1394 def descends_from_active_record?
1395 if superclass.abstract_class?
1396 superclass.descends_from_active_record?
1397 else
1398 superclass == Base || !columns_hash.include?(inheritance_column)
1399 end
db045dbb » dhh 2004-11-23 Initial 1400 end
1401
b4ec9904 » NZKoz 2007-10-02 Cache the descends_from_act... 1402 def finder_needs_type_condition? #:nodoc:
1403 # This is like this because benchmarking justifies the strange :false stuff
1404 :true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true)
1405 end
1406
d0360a4d » jeremy 2007-05-31 Base.inspect handles Base i... 1407 # Returns a string like 'Post id:integer, title:string, body:text'
52a9e508 » dhh 2007-04-21 Added ActiveRecord::Base.in... 1408 def inspect
d0360a4d » jeremy 2007-05-31 Base.inspect handles Base i... 1409 if self == Base
1410 super
1411 elsif abstract_class?
1412 "#{super}(abstract)"
bb94ce92 » NZKoz 2007-08-05 Let inspect on AR classes w... 1413 elsif table_exists?
d0360a4d » jeremy 2007-05-31 Base.inspect handles Base i... 1414 attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', '
1415 "#{super}(#{attr_list})"
bb94ce92 » NZKoz 2007-08-05 Let inspect on AR classes w... 1416 else
1417 "#{super}(Table doesn't exist)"
d0360a4d » jeremy 2007-05-31 Base.inspect handles Base i... 1418 end
52a9e508 » dhh 2007-04-21 Added ActiveRecord::Base.in... 1419 end
1420
b445ab98 » NZKoz 2006-09-04 Rename quote to quote_value... 1421 def quote_value(value, column = nil) #:nodoc:
b2c0ddf0 » Marcel Molina 2006-04-27 Add support for FrontBase (... 1422 connection.quote(value,column)
49403831 » dhh 2004-12-07 Fixed value quoting in all ... 1423 end
1424
7143d801 » Marcel Molina 2007-11-07 Smattering of grammatical f... 1425 # Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>.
4eab3758 » dhh 2005-02-23 Finished polishing API docs 1426 def sanitize(object) #:nodoc:
49403831 » dhh 2004-12-07 Fixed value quoting in all ... 1427 connection.quote(object)
db045dbb » dhh 2004-11-23 Initial 1428 end
1429
f2a89d78 » dhh 2005-09-06 Give AR the new benchmark m... 1430 # Log and benchmark multiple statements in a single block. Example:
db045dbb » dhh 2004-11-23 Initial 1431 #
1432 # Project.benchmark("Creating project") do
1433 # project = Project.create("name" => "stuff")
1434 # project.create_manager("name" => "David")
3dfa56cc » dhh 2005-06-26 Updated all references to t... 1435 # project.milestones << Milestone.find(:all)
db045dbb » dhh 2004-11-23 Initial 1436 # end
5e8e8d65 » dhh 2005-09-06 Added use_silence parameter... 1437 #
15b38efd » jeremy 2007-12-20 Benchmark logs for any leve... 1438 # The benchmark is only recorded if the current level of the logger is less than or equal to the <tt>log_level</tt>,
1439 # which makes it easy to include benchmarking statements in production software that will remain inexpensive because
1440 # the benchmark will only be conducted if the log level is low enough.
f2a89d78 » dhh 2005-09-06 Give AR the new benchmark m... 1441 #
2948910b » Marcel Molina 2005-10-10 Misc doc fixes (typos/gramm... 1442 # The logging of the multiple statements is turned off unless <tt>use_silence</tt> is set to false.
f2a89d78 » dhh 2005-09-06 Give AR the new benchmark m... 1443 def benchmark(title, log_level = Logger::DEBUG, use_silence = true)
15b38efd » jeremy 2007-12-20 Benchmark logs for any leve... 1444 if logger && logger.level <= log_level
5e8e8d65 » dhh 2005-09-06 Added use_silence parameter... 1445 result = nil
e8c4939f » jeremy 2008-12-09 Benchmark.ms 1446 ms = Benchmark.ms { result = use_silence ? silence { yield } : yield }
1447 logger.add(log_level, '%s (%.1fms)' % [title, ms])
5e8e8d65 » dhh 2005-09-06 Added use_silence parameter... 1448 result
1449 else
1450 yield
1451 end
c00bf5f0 » dhh 2005-02-16 Fixed the verbosity of usin... 1452 end
81737fc0 » jeremy 2005-07-03 r1613@asus: jeremy | 2005... 1453
c00bf5f0 » dhh 2005-02-16 Fixed the verbosity of usin... 1454 # Silences the logger for the duration of the block.
1455 def silence
81737fc0 » jeremy 2005-07-03 r1613@asus: jeremy | 2005... 1456 old_logger_level, logger.level = logger.level, Logger::ERROR if logger
1457 yield
1458 ensure
908e9a17 » dhh 2005-04-12 Fixed that Base.silence sho... 1459 logger.level = old_logger_level if logger
db045dbb » dhh 2004-11-23 Initial 1460 end
390e6d24 » jeremy 2005-11-06 r2915@asus: jeremy | 2005... 1461
97849deb » dhh 2005-01-23 Fixed that association prox... 1462 # Overwrite the default class equality method to provide support for association proxies.
1463 def ===(object)
1464 object.is_a?(self)
73673256 » jeremy 2007-12-09 Document Active Record exce... 1465 end
b840e4ed » Marcel Molina 2005-10-12 Deprecated ActiveRecord::Ba... 1466
d2f47503 » jamis 2006-01-20 Add AR::Base.base_class for... 1467 # Returns the base AR subclass that this class descends from. If A
1468 # extends AR::Base, A.base_class will return A. If B descends from A
1469 # through some arbitrarily deep hierarchy, B.base_class will return A.
1470 def base_class
1471 class_of_active_record_descendant(self)
1472 end
1473
98dc5827 » lifo 2008-05-25 Merge docrails. Comment 1474 # Set this to true if this is an abstract class (see <tt>abstract_class?</tt>).
def74603 » technoweenie 2006-03-15 Added Base.abstract_class? ... 1475 attr_accessor :abstract_class
1476
1477 # Returns whether this class is a base AR class. If A is a base class and
1478 # B descends from A, then B.base_class will return B.
1479 def abstract_class?
8b5f4e47 » jeremy 2007-12-22 Ruby 1.9 compat: fix warnin... 1480 defined?(@abstract_class) && @abstract_class == true
def74603 » technoweenie 2006-03-15 Added Base.abstract_class? ... 1481 end
1482
4f39382a » lifo 2008-04-06 Ensure that respond_to? con... 1483 def respond_to?(method_id, include_private = false)
143f5fbb » joshsusser 2008-08-25 refactor dynamic finder nam... 1484 if match = DynamicFinderMatch.match(method_id)
1485 return true if all_attributes_exists?(match.attribute_names)
66ee5890 » yaroslav 2008-12-28 Introduce dynamic scopes fo... Comment 1486 elsif match = DynamicScopeMatch.match(method_id)
1487 return true if all_attributes_exists?(match.attribute_names)
4f39382a » lifo 2008-04-06 Ensure that respond_to? con... 1488 end
c3aa2bcd » Manfred 2009-03-10 Ensure nested with_scope me... 1489
4f39382a » lifo 2008-04-06 Ensure that respond_to? con... 1490 super
1491 end
1492
72483c0d » technoweenie 2008-05-31 Add ActiveRecord::Base.sti_... 1493 def sti_name
1494 store_full_sti_class ? name : name.demodulize
1495 end
1496
e328bdaa » jeremy 2008-06-17 Make Base.merge_conditions ... 1497 # Merges conditions so that the result is a valid +condition+
1498 def merge_conditions(*conditions)
1499 segments = []
1500
1501 conditions.each do |condition|
1502 unless condition.blank?
1503 sql = sanitize_sql(condition)
1504 segments << sql unless sql.blank?
1505 end
1506 end
1507
1508 "(#{segments.join(') AND (')})" unless segments.empty?
1509 end
1510
db045dbb » dhh 2004-11-23 Initial 1511 private
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1512 def find_initial(options)
361aaa04 » Aliaksey Kandratsenka 2008-01-15 Remove old :limit removal c... Comment 1513 options.update(:limit => 1)
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1514 find_every(options).first
1515 end
2fbe0ae7 » jeremy 2006-11-05 Support nil and Array in :c... 1516
d5a4d5ab » dhh 2008-03-12 Added ActiveRecord::Base.fi... 1517 def find_last(options)
1518 order = options[:order]
1519
1520 if order
1521 order = reverse_sql_order(order)
1522 elsif !scoped?(:find, :order)
1523 order = "#{table_name}.#{primary_key} DESC"
1524 end
1525
1526 if scoped?(:find, :order)
f7bd0beb » Daniel Luz 2008-12-21 Ensure Model#last doesn't a... 1527 scope = scope(:find)
1528 original_scoped_order = scope[:order]
1529 scope[:order] = reverse_sql_order(original_scoped_order)
d5a4d5ab » dhh 2008-03-12 Added ActiveRecord::Base.fi... 1530 end
3b0e1d90 » josh 2008-05-14 Prefer string core_ext infl... Comment 1531
f7bd0beb » Daniel Luz 2008-12-21 Ensure Model#last doesn't a... 1532 begin
1533 find_initial(options.merge({ :order => order }))
1534 ensure
1535 scope[:order] = original_scoped_order if original_scoped_order
1536 end
d5a4d5ab » dhh 2008-03-12 Added ActiveRecord::Base.fi... 1537 end
1538
1539 def reverse_sql_order(order_query)
faf4ba6b » rob-at-thewebfellas 2009-03-09 Allow find(:last) :order be... 1540 reversed_query = order_query.to_s.split(/,/).each { |s|
d5a4d5ab » dhh 2008-03-12 Added ActiveRecord::Base.fi... 1541 if s.match(/\s(asc|ASC)$/)
1542 s.gsub!(/\s(asc|ASC)$/, ' DESC')
1543 elsif s.match(/\s(desc|DESC)$/)
1544 s.gsub!(/\s(desc|DESC)$/, ' ASC')
3b0e1d90 » josh 2008-05-14 Prefer string core_ext infl... Comment 1545 elsif !s.match(/\s(asc|ASC|desc|DESC)$/)
d5a4d5ab » dhh 2008-03-12 Added ActiveRecord::Base.fi... 1546 s.concat(' DESC')
1547 end
1548 }.join(',')
1549 end
3b0e1d90 » josh 2008-05-14 Prefer string core_ext infl... Comment 1550
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1551 def find_every(options)
355a8ff2 » jeremy 2008-01-18 Introduce preload query str... 1552 include_associations = merge_includes(scope(:find, :include), options[:include])
1553
1554 if include_associations.any? && references_eager_loaded_tables?(options)
1555 records = find_with_associations(options)
1556 else
1557 records = find_by_sql(construct_finder_sql(options))
1558 if include_associations.any?
1559 preload_associations(records, include_associations)
1560 end
1561 end
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1562
1563 records.each { |record| record.readonly! } if options[:readonly]
1564
1565 records
1566 end
2fbe0ae7 » jeremy 2006-11-05 Support nil and Array in :c... 1567
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1568 def find_from_ids(ids, options)
2fbe0ae7 » jeremy 2006-11-05 Support nil and Array in :c... 1569 expects_array = ids.first.kind_of?(Array)
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1570 return ids.first if expects_array && ids.first.empty?
2fbe0ae7 » jeremy 2006-11-05 Support nil and Array in :c... 1571
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1572 ids = ids.flatten.compact.uniq
1573
1574 case ids.size
1575 when 0
1576 raise RecordNotFound, "Couldn't find #{name} without an ID"
1577 when 1
1578 result = find_one(ids.first, options)
1579 expects_array ? [ result ] : result
1580 else
1581 find_some(ids, options)
1582 end
1583 end
73673256 » jeremy 2007-12-09 Document Active Record exce... 1584
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1585 def find_one(id, options)
1586 conditions = " AND (#{sanitize_sql(options[:conditions])})" if options[:conditions]
9b6207c3 » jeremy 2007-10-15 Quote table names. Defaults... 1587 options.update :conditions => "#{quoted_table_name}.#{connection.quote_column_name(primary_key)} = #{quote_value(id,columns_hash[primary_key])}#{conditions}"
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1588
230c5a06 » jeremy 2006-07-07 find_one uses find_every.fi... 1589 # Use find_every(options).first since the primary key condition
1590 # already ensures we have a single record. Using find_initial adds
1591 # a superfluous :limit => 1.
1592 if result = find_every(options).first
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1593 result
1594 else
1595 raise RecordNotFound, "Couldn't find #{name} with ID=#{id}#{conditions}"
1596 end
1597 end
73673256 » jeremy 2007-12-09 Document Active Record exce... 1598
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1599 def find_some(ids, options)
1600 conditions = " AND (#{sanitize_sql(options[:conditions])})" if options[:conditions]
b445ab98 » NZKoz 2006-09-04 Rename quote to quote_value... 1601 ids_list = ids.map { |id| quote_value(id,columns_hash[primary_key]) }.join(',')
9b6207c3 » jeremy 2007-10-15 Quote table names. Defaults... 1602 options.update :conditions => "#{quoted_table_name}.#{connection.quote_column_name(primary_key)} IN (#{ids_list})#{conditions}"
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1603
1604 result = find_every(options)
1605
8158455d » jeremy 2007-05-31 Fix an edge case with find ... 1606 # Determine expected size from limit and offset, not just ids.size.
109926c5 » jeremy 2007-05-25 Find with a list of ids sup... 1607 expected_size =
1608 if options[:limit] && ids.size > options[:limit]
1609 options[:limit]
1610 else
1611 ids.size
1612 end
8158455d » jeremy 2007-05-31 Fix an edge case with find ... 1613
1614 # 11 ids with limit 3, offset 9 should give 2 results.
1615 if options[:offset] && (ids.size - options[:offset] < expected_size)
1616 expected_size = ids.size - options[:offset]
1617 end
109926c5 » jeremy 2007-05-25 Find with a list of ids sup... 1618
1619 if result.size == expected_size
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1620 result
1621 else
109926c5 » jeremy 2007-05-25 Find with a list of ids sup... 1622 raise RecordNotFound, "Couldn't find all #{name.pluralize} with IDs (#{ids_list})#{conditions} (found #{result.size} results, but was looking for #{expected_size})"
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1623 end
1624 end
1625
4b4dd540 » jeremy 2006-08-23 Clashing type columns due t... 1626 # Finder methods must instantiate through this method to work with the
1627 # single-table inheritance model that makes it possible to create
1628 # objects of different types from the same table.
db045dbb » dhh 2004-11-23 Initial 1629 def instantiate(record)
4b4dd540 » jeremy 2006-08-23 Clashing type columns due t... 1630 object =
eb2fbf05 » Marcel Molina 2005-10-09 Optimize instantiation of S... 1631 if subclass_name = record[inheritance_column]
4b4dd540 » jeremy 2006-08-23 Clashing type columns due t... 1632 # No type given.
eb2fbf05 » Marcel Molina 2005-10-09 Optimize instantiation of S... 1633 if subclass_name.empty?
1634 allocate
4b4dd540 » jeremy 2006-08-23 Clashing type columns due t... 1635
eb2fbf05 » Marcel Molina 2005-10-09 Optimize instantiation of S... 1636 else
4b4dd540 » jeremy 2006-08-23 Clashing type columns due t... 1637 # Ignore type if no column is present since it was probably
1638 # pulled in from a sloppy join.
9d2da046 » jeremy 2006-11-09 Cache inheritance_column. C... 1639 unless columns_hash.include?(inheritance_column)
4b4dd540 » jeremy 2006-08-23 Clashing type columns due t... 1640 allocate
1641
1642 else
1643 begin
1644 compute_type(subclass_name).allocate
1645 rescue NameError
1646 raise SubclassNotFound,
1647 "The single-table inheritance mechanism failed to locate the subclass: '#{record[inheritance_column]}'. " +
1648 "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " +
1649 "Please rename this column if you didn't intend it to be used for storing the inheritance class " +
1650 "or overwrite #{self.to_s}.inheritance_column to use another column for that information."
1651 end
eb2fbf05 » Marcel Molina 2005-10-09 Optimize instantiation of S... 1652 end
1653 end
1654 else
1655 allocate
81737fc0 » jeremy 2005-07-03 r1613@asus: jeremy | 2005... 1656 end
605bc775 » dhh 2004-12-14 Added a better exception fo... 1657
db045dbb » dhh 2004-11-23 Initial 1658 object.instance_variable_set("@attributes", record)
5b801b59 » NZKoz 2007-08-14 Change the implementation o... 1659 object.instance_variable_set("@attributes_cache", Hash.new)
55efae23 » jeremy 2007-08-30 Performance: absorb instant... 1660
1661 if object.respond_to_without_attributes?(:after_find)
1662 object.send(:callback, :after_find)
1663 end
1664
1665 if object.respond_to_without_attributes?(:after_initialize)
1666 object.send(:callback, :after_initialize)
1667 end
1668
81737fc0 » jeremy 2005-07-03 r1613@asus: jeremy | 2005... 1669 object
db045dbb » dhh 2004-11-23 Initial 1670 end
81737fc0 » jeremy 2005-07-03 r1613@asus: jeremy | 2005... 1671
c7d6d68f » jeremy 2006-02-22 Reflections don't attempt t... 1672 # Nest the type name in the same module as this class.
1673 # Bar is "MyApp::Business::Bar" relative to MyApp::Business::Foo
db045dbb » dhh 2004-11-23 Initial 1674 def type_name_with_module(type_name)
72483c0d » technoweenie 2008-05-31 Add ActiveRecord::Base.sti_... 1675 if store_full_sti_class
1676 type_name
1677 else
1678 (/^::/ =~ type_name) ? type_name : "#{parent.name}::#{type_name}"
1679 end
db045dbb » dhh 2004-11-23 Initial 1680 end
1681
789a3f5b » willbryant 2008-11-13 Moved the * strings out of ... 1682 def default_select(qualified)
1683 if qualified
1684 quoted_table_name + '.*'
1685 else
1686 '*'
1687 end
1688 end
1689
abc895b8 » dhh 2005-04-03 Added new Base.find API and... 1690 def construct_finder_sql(options)
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1691 scope = scope(:find)
789a3f5b » willbryant 2008-11-13 Moved the * strings out of ... 1692 sql = "SELECT #{options[:select] || (scope && scope[:select]) || default_select(options[:joins] || (scope && scope[:joins]))} "
4863634a » lifo 2009-03-06 Ensure supplie :from has pr... Comment 1693 sql << "FROM #{options[:from] || (scope && scope[:from]) || quoted_table_name} "
6abda696 » dhh 2005-12-02 Added preliminary support f... 1694
db22c895 » pixeltrix 2008-08-28 Merge scoped :joins togethe... 1695 add_joins!(sql, options[:joins], scope)
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1696 add_conditions!(sql, options[:conditions], scope)
6abda696 » dhh 2005-12-02 Added preliminary support f... 1697
97403ad5 » miloops 2008-11-21 Add :having option to find,... 1698 add_group!(sql, options[:group], options[:having], scope)
57a3e440 » jamis 2006-11-07 make add_order a tad faster... 1699 add_order!(sql, options[:order], scope)
c9c18520 » dhh 2006-03-27 Making ActiveRecord faster ... 1700 add_limit!(sql, options, scope)
15aa6e05 » jeremy 2006-06-19 r4644@asus: jeremy | 2006... 1701 add_lock!(sql, options, scope)
6abda696 » dhh 2005-12-02 Added preliminary support f... 1702
6e39c9e5 » jeremy 2005-07-03 r1614@asus: jeremy | 2005... 1703 sql
efb55d1c » dhh 2005-04-03 Allow order, conditions, an... 1704 end
abc895b8 » dhh 2005-04-03 Added new Base.find API and... 1705
445cb5c0 » NZKoz 2006-03-26 Add support for :include to... 1706 # Merges includes so that the result is a valid +include+
1707 def merge_includes(first, second)
01a52dd1 » dhh 2006-06-03 Fixed that :includes merged... 1708 (safe_to_array(first) + safe_to_array(second)).uniq
445cb5c0 » NZKoz 2006-03-26 Add support for :include to... 1709 end
1710
487758b3 » Pivotal Labs 2008-09-23 Allowed passing arrays-of-s... 1711 def merge_joins(*joins)
1712 if joins.any?{|j| j.is_a?(String) || array_of_strings?(j) }
1713 joins = joins.collect do |join|
1714 join = [join] if join.is_a?(String)
1715 unless array_of_strings?(join)
1716 join_dependency = ActiveRecord::Associations::ClassMethods::InnerJoinDependency.new(self, join, nil)
1717 join = join_dependency.join_associations.collect { |assoc| assoc.association_join }
1718 end
1719 join
db22c895 » pixeltrix 2008-08-28 Merge scoped :joins togethe... 1720 end
a0d8202b » FiXato 2008-10-30 Ensure whitespaces are stri... 1721 joins.flatten.map{|j| j.strip}.uniq
db22c895 » pixeltrix 2008-08-28 Merge scoped :joins togethe... 1722 else
487758b3 » Pivotal Labs 2008-09-23 Allowed passing arrays-of-s... 1723 joins.collect{|j| safe_to_array(j)}.flatten.uniq
db22c895 » pixeltrix 2008-08-28 Merge scoped :joins togethe... 1724 end
1725 end
1726
48052d70 » jeremy 2006-06-02 to_xml fixes, features, and... 1727 # Object#to_a is deprecated, though it does have the desired behavior
445cb5c0 » NZKoz 2006-03-26 Add support for :include to... 1728 def safe_to_array(o)
1729 case o
1730 when NilClass
1731 []
1732 when Array
1733 o
1734 else
1735 [o]
1736 end
1737 end
1738
487758b3 » Pivotal Labs 2008-09-23 Allowed passing arrays-of-s... 1739 def array_of_strings?(o)
1740 o.is_a?(Array) && o.all?{|obj| obj.is_a?(String)}
1741 end
1742
57a3e440 » jamis 2006-11-07 make add_order a tad faster... 1743 def add_order!(sql, order, scope = :auto)
1744 scope = scope(:find) if :auto == scope
1745 scoped_order = scope[:order] if scope
91531372 » Marcel Molina 2006-04-25 Add support for :order opti... 1746 if order
1747 sql << " ORDER BY #{order}"
19ad375e » jeremy 2009-03-10