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