Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100755 1333 lines (1175 sloc) 62.167 kb
dc3d6eb @dhh Moved Active Support into its own gem
dhh authored
1 require 'active_support/class_attribute_accessors'
2 require 'active_support/class_inheritable_attributes'
3 require 'active_support/inflector'
db045db @dhh Initial
dhh authored
4 require 'yaml'
5
6 module ActiveRecord #:nodoc:
7 class ActiveRecordError < StandardError #:nodoc:
8 end
605bc77 @dhh Added a better exception for when a type column is used in a table witho...
dhh authored
9 class SubclassNotFound < ActiveRecordError #:nodoc:
10 end
db045db @dhh Initial
dhh authored
11 class AssociationTypeMismatch < ActiveRecordError #:nodoc:
12 end
13 class SerializationTypeMismatch < ActiveRecordError #:nodoc:
14 end
15 class AdapterNotSpecified < ActiveRecordError # :nodoc:
16 end
17 class AdapterNotFound < ActiveRecordError # :nodoc:
18 end
19 class ConnectionNotEstablished < ActiveRecordError #:nodoc:
20 end
21 class ConnectionFailed < ActiveRecordError #:nodoc:
22 end
23 class RecordNotFound < ActiveRecordError #:nodoc:
24 end
25 class StatementInvalid < ActiveRecordError #:nodoc:
26 end
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
27 class PreparedStatementInvalid < ActiveRecordError #:nodoc:
28 end
fbf9281 @dhh Added automated optimistic locking if the field lock_version is present ...
dhh authored
29 class StaleObjectError < ActiveRecordError #:nodoc:
30 end
db045db @dhh Initial
dhh authored
31
32 # Active Record objects doesn't specify their attributes directly, but rather infer them from the table definition with
33 # which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change
34 # is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain
35 # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
36 #
37 # See the mapping rules in table_name and the full example in link:files/README.html for more insight.
38 #
39 # == Creation
40 #
41 # Active Records accepts constructor parameters either in a hash or as a block. The hash method is especially useful when
42 # you're receiving the data from somewhere else, like a HTTP request. It works like this:
43 #
44 # user = User.new("name" => "David", "occupation" => "Code Artist")
45 # user.name # => "David"
46 #
47 # You can also use block initialization:
48 #
49 # user = User.new do |u|
50 # u.name = "David"
51 # u.occupation = "Code Artist"
52 # end
53 #
54 # And of course you can just create a bare object and specify the attributes after the fact:
55 #
56 # user = User.new
57 # user.name = "David"
58 # user.occupation = "Code Artist"
59 #
60 # == Conditions
61 #
62 # Conditions can either be specified as a string or an array representing the WHERE-part of an SQL statement.
63 # The array form is to be used when the condition input is tainted and requires sanitization. The string form can
64 # be used for statements that doesn't involve tainted data. Examples:
65 #
66 # User < ActiveRecord::Base
67 # def self.authenticate_unsafely(user_name, password)
68 # find_first("user_name = '#{user_name}' AND password = '#{password}'")
69 # end
70 #
71 # def self.authenticate_safely(user_name, password)
3e7d191 @dhh Added bind-style variable interpolation for the condition arrays that us...
dhh authored
72 # find_first([ "user_name = ? AND password = ?", user_name, password ])
db045db @dhh Initial
dhh authored
73 # end
74 # end
75 #
2575b3b @dhh Added extra words of caution for guarding against SQL-injection attacks
dhh authored
76 # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection
77 # attacks if the <tt>user_name</tt> and +password+ parameters come directly from a HTTP request. The <tt>authenticate_safely</tt> method,
78 # on the other hand, will sanitize the <tt>user_name</tt> and +password+ before inserting them in the query, which will ensure that
db045db @dhh Initial
dhh authored
79 # an attacker can't escape the query and fake the login (or worse).
2575b3b @dhh Added extra words of caution for guarding against SQL-injection attacks
dhh authored
80 #
db045db @dhh Initial
dhh authored
81 # == Overwriting default accessors
82 #
83 # All column values are automatically available through basic accessors on the Active Record object, but some times you
84 # want to specialize this behavior. This can be done by either by overwriting the default accessors (using the same
85 # name as the attribute) calling read_attribute(attr_name) and write_attribute(attr_name, value) to actually change things.
86 # Example:
87 #
88 # class Song < ActiveRecord::Base
89 # # Uses an integer of seconds to hold the length of the song
90 #
91 # def length=(minutes)
92 # write_attribute("length", minutes * 60)
93 # end
94 #
95 # def length
96 # read_attribute("length") / 60
97 # end
98 # end
99 #
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting object...
dhh authored
100 # == Dynamic attribute-based finders
101 #
102 # Dynamic attribute-based finders are a cleaner way of getting objects by simple queries without turning to SQL. They work by
103 # appending the name of an attribute to <tt>find_by_</tt>, so you get finders like <tt>Person.find_by_user_name, Payment.find_by_transaction_id</tt>.
104 # So instead of writing <tt>Person.find_first(["user_name = ?", user_name])</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
105 #
106 # It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like
107 # <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
108 # <tt>Person.find_first(["user_name = ? AND password = ?", user_name, password])</tt>, you just do
109 # <tt>Person.find_by_user_name_and_password(user_name, password)</tt>.
569f2ea @dhh Added the possibility of specifying the remaining options for find_first...
dhh authored
110 #
111 # It's even possible to use all the additional parameters to find_first and find_all. For example, the full interface for Payment.find_all_by_amount
112 # is actually Payment.find_all_by_amount(amount, orderings = nil, limit = nil, joins = nil). And the full interface to Person.find_by_user_name is
113 # actually Person.find_by_user_name(user_name, orderings = nil)
959f362 @dhh Added find_all style to the new dynamic finders
dhh authored
114 #
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
115 # == Saving arrays, hashes, and other non-mappable objects in text columns
db045db @dhh Initial
dhh authored
116 #
117 # 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+.
118 # This makes it possible to store arrays, hashes, and other non-mappeable objects without doing any additional work. Example:
119 #
120 # class User < ActiveRecord::Base
121 # serialize :preferences
122 # end
123 #
124 # user = User.create("preferences" => { "background" => "black", "display" => large })
125 # User.find(user.id).preferences # => { "background" => "black", "display" => large }
126 #
66f44e6 @dhh Updated documentation for serialize
dhh authored
127 # You can also specify an class option as the second parameter that'll raise an exception if a serialized object is retrieved as a
db045db @dhh Initial
dhh authored
128 # descendent of a class not in the hierarchy. Example:
129 #
130 # class User < ActiveRecord::Base
66f44e6 @dhh Updated documentation for serialize
dhh authored
131 # serialize :preferences, Hash
db045db @dhh Initial
dhh authored
132 # end
133 #
134 # user = User.create("preferences" => %w( one two three ))
135 # User.find(user.id).preferences # raises SerializationTypeMismatch
136 #
137 # == Single table inheritance
138 #
139 # Active Record allows inheritance by storing the name of the class in a column that by default is called "type" (can be changed
140 # by overwriting <tt>Base.inheritance_column</tt>). This means that an inheritance looking like this:
141 #
142 # class Company < ActiveRecord::Base; end
143 # class Firm < Company; end
144 # class Client < Company; end
145 # class PriorityClient < Client; end
146 #
147 # When you do Firm.create("name" => "37signals"), this record with be saved in the companies table with type = "Firm". You can then
148 # fetch this row again using Company.find_first "name = '37signals'" and it will return a Firm object.
149 #
f033833 @dhh Improving documentation...
dhh authored
150 # 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
151 # like normal subclasses with no special magic for differentiating between them or reloading the right type with find.
152 #
db045db @dhh Initial
dhh authored
153 # Note, all the attributes for all the cases are kept in the same table. Read more:
154 # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
155 #
156 # == Connection to multiple databases in different models
157 #
158 # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection.
159 # All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection.
160 # For example, if Course is a ActiveRecord::Base, but resides in a different database you can just say Course.establish_connection
161 # and Course *and all its subclasses* will use this connection instead.
162 #
163 # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is
164 # requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool.
165 #
166 # == Exceptions
167 #
168 # * +ActiveRecordError+ -- generic error class and superclass of all other errors raised by Active Record
169 # * +AdapterNotSpecified+ -- the configuration hash used in <tt>establish_connection</tt> didn't include a
170 # <tt>:adapter</tt> key.
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
171 # * +AdapterNotSpecified+ -- the <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified an non-existent adapter
db045db @dhh Initial
dhh authored
172 # (or a bad spelling of an existing one).
173 # * +AssociationTypeMismatch+ -- the object assigned to the association wasn't of the type specified in the association definition.
66f44e6 @dhh Updated documentation for serialize
dhh authored
174 # * +SerializationTypeMismatch+ -- the object serialized wasn't of the class specified as the second parameter.
db045db @dhh Initial
dhh authored
175 # * +ConnectionNotEstablished+ -- no connection has been established. Use <tt>establish_connection</tt> before querying.
176 # * +RecordNotFound+ -- no record responded to the find* method.
177 # Either the row with the given ID doesn't exist or the row didn't meet the additional restrictions.
178 # * +StatementInvalid+ -- the database server rejected the SQL statement. The precise error is added in the message.
179 # Either the record with the given ID doesn't exist or the record didn't meet the additional restrictions.
180 #
181 # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
182 # So it's possible to assign a logger to the class through Base.logger= which will then be used by all
183 # instances in the current object space.
184 class Base
185 include ClassInheritableAttributes
186
187 # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed
188 # on to any new database connections made and which can be retrieved on both a class and instance level by calling +logger+.
189 cattr_accessor :logger
190
191 # Returns the connection currently associated with the class. This can
192 # also be used to "borrow" the connection to do database work unrelated
193 # to any of the specific Active Records.
194 def self.connection
195 retrieve_connection
196 end
197
198 # Returns the connection currently associated with the class. This can
199 # also be used to "borrow" the connection to do database work that isn't
200 # easily done without going straight to SQL.
201 def connection
202 self.class.connection
203 end
204
205 def self.inherited(child) #:nodoc:
206 @@subclasses[self] ||= []
207 @@subclasses[self] << child
208 super
209 end
210
211 @@subclasses = {}
8e1f1ee @dhh Moved require_association to associations.rb and added methods for reset...
dhh authored
212
db045db @dhh Initial
dhh authored
213 cattr_accessor :configurations
214 @@primary_key_prefix_type = {}
215
216 # Accessor for the prefix type that will be prepended to every primary key column name. The options are :table_name and
217 # :table_name_with_underscore. If the first is specified, the Product class will look for "productid" instead of "id" as
218 # the primary column. If the latter is specified, the Product class will look for "product_id" instead of "id". Remember
219 # that this is a global setting for all Active Records.
220 cattr_accessor :primary_key_prefix_type
221 @@primary_key_prefix_type = nil
222
223 # Accessor for the name of the prefix string to prepend to every table name. So if set to "basecamp_", all
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
224 # table names will be named like "basecamp_projects", "basecamp_people", etc. This is a convenient way of creating a namespace
db045db @dhh Initial
dhh authored
225 # for tables in a shared database. By default, the prefix is the empty string.
226 cattr_accessor :table_name_prefix
227 @@table_name_prefix = ""
228
229 # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
230 # "people_basecamp"). By default, the suffix is the empty string.
231 cattr_accessor :table_name_suffix
232 @@table_name_suffix = ""
233
234 # Indicate whether or not table names should be the pluralized versions of the corresponding class names.
235 # If true, this the default table name for a +Product+ class will be +products+. If false, it would just be +product+.
236 # See table_name for the full rules on table/class naming. This is true, by default.
237 cattr_accessor :pluralize_table_names
238 @@pluralize_table_names = true
239
60de8c1 @dhh Added Base.default_timezone accessor that determines whether to use Time...
dhh authored
240 # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates and times from the database.
241 # This is set to :local by default.
242 cattr_accessor :default_timezone
243 @@default_timezone = :local
244
db045db @dhh Initial
dhh authored
245 class << self # Class methods
246 # Returns objects for the records responding to either a specific id (1), a list of ids (1, 5, 6) or an array of ids.
247 # If only one ID is specified, that object is returned directly. If more than one ID is specified, an array is returned.
248 # Examples:
249 # Person.find(1) # returns the object for ID = 1
250 # Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
251 # Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
57ed93e @dhh Fixed that Base#find will return an array if given an array -- regardles...
dhh authored
252 # Person.find([1]) # returns an array for objects the object with ID = 1
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
253 #
254 # The last argument may be a Hash of find options. Currently, +conditions+ is the only option, behaving the same as with +find_all+.
569f2ea @dhh Added the possibility of specifying the remaining options for find_first...
dhh authored
255 # Person.find(1, :conditions => "associate_id = 5"
256 # Person.find(1, 2, 6, :conditions => "status = 'active'"
257 # Person.find([7, 17], :conditions => ["sanitize_me = ?", "bare'quote"]
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
258 #
db045db @dhh Initial
dhh authored
259 # +RecordNotFound+ is raised if no record can be found.
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
260 def find(*args)
261 # Return an Array if ids are passed in an Array.
262 expects_array = args.first.kind_of?(Array)
263
264 # Extract options hash from argument list.
265 options = extract_options_from_args!(args)
266 conditions = " AND #{sanitize_sql(options[:conditions])}" if options[:conditions]
267
268 ids = args.flatten.compact.uniq
269 case ids.size
270
271 # Raise if no ids passed.
272 when 0
273 raise RecordNotFound, "Couldn't find #{name} without an ID#{conditions}"
274
275 # Find a single id.
276 when 1
277 unless result = find_first("#{primary_key} = #{sanitize(ids.first)}#{conditions}")
278 raise RecordNotFound, "Couldn't find #{name} with ID=#{ids.first}#{conditions}"
279 end
db045db @dhh Initial
dhh authored
280
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
281 # Box result if expecting array.
282 expects_array ? [result] : result
db045db @dhh Initial
dhh authored
283
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
284 # Find multiple ids.
db045db @dhh Initial
dhh authored
285 else
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
286 ids_list = ids.map { |id| sanitize(id) }.join(',')
287 result = find_all("#{primary_key} IN (#{ids_list})#{conditions}", primary_key)
288 if result.size == ids.size
289 result
290 else
872ddaf @dhh Added bind-named arrays for interpolating a group of ids or strings in c...
dhh authored
291 raise RecordNotFound, "Couldn't find all #{name.pluralize} with IDs (#{ids_list})#{conditions}"
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
292 end
db045db @dhh Initial
dhh authored
293 end
294 end
295
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
296 # This method is deprecated in favor of find with the :conditions option.
db045db @dhh Initial
dhh authored
297 # Works like find, but the record matching +id+ must also meet the +conditions+.
298 # +RecordNotFound+ is raised if no record can be found matching the +id+ or meeting the condition.
299 # Example:
300 # Person.find_on_conditions 5, "first_name LIKE '%dav%' AND last_name = 'heinemeier'"
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
301 def find_on_conditions(ids, conditions)
302 find(ids, :conditions => conditions)
db045db @dhh Initial
dhh authored
303 end
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
304
db045db @dhh Initial
dhh authored
305 # Returns an array of all the objects that could be instantiated from the associated
306 # table in the database. The +conditions+ can be used to narrow the selection of objects (WHERE-part),
307 # such as by "color = 'red'", and arrangement of the selection can be done through +orderings+ (ORDER BY-part),
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in regu...
dhh authored
308 # such as by "last_name, first_name DESC". A maximum of returned objects and their offset can be specified in
309 # +limit+ (LIMIT...OFFSET-part). Examples:
db045db @dhh Initial
dhh authored
310 # Project.find_all "category = 'accounts'", "last_accessed DESC", 15
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in regu...
dhh authored
311 # Project.find_all ["category = ?", category_name], "created ASC", ["? OFFSET ?", 15, 20]
db045db @dhh Initial
dhh authored
312 def find_all(conditions = nil, orderings = nil, limit = nil, joins = nil)
313 sql = "SELECT * FROM #{table_name} "
314 sql << "#{joins} " if joins
315 add_conditions!(sql, conditions)
316 sql << "ORDER BY #{orderings} " unless orderings.nil?
4cd9c95 @dhh Added the possibility for adapters to overwrite add_limit! to implement ...
dhh authored
317
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
318 connection.add_limit!(sql, sanitize_sql(limit)) unless limit.nil?
4cd9c95 @dhh Added the possibility for adapters to overwrite add_limit! to implement ...
dhh authored
319
db045db @dhh Initial
dhh authored
320 find_by_sql(sql)
321 end
322
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in regu...
dhh authored
323 # Works like find_all, but requires a complete SQL string. Examples:
db045db @dhh Initial
dhh authored
324 # Post.find_by_sql "SELECT p.*, c.author FROM posts p, comments c WHERE p.id = c.post_id"
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in regu...
dhh authored
325 # Post.find_by_sql ["SELECT * FROM posts WHERE author = ? AND created > ?", author_id, start_date]
db045db @dhh Initial
dhh authored
326 def find_by_sql(sql)
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
327 connection.select_all(sanitize_sql(sql), "#{name} Load").inject([]) { |objects, record| objects << instantiate(record) }
db045db @dhh Initial
dhh authored
328 end
329
330 # Returns the object for the first record responding to the conditions in +conditions+,
331 # such as "group = 'master'". If more than one record is returned from the query, it's the first that'll
332 # be used to create the object. In such cases, it might be beneficial to also specify
333 # +orderings+, like "income DESC, name", to control exactly which record is to be used. Example:
334 # Employee.find_first "income > 50000", "income DESC, name"
335 def find_first(conditions = nil, orderings = nil)
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
336 find_all(conditions, orderings, 1).first
db045db @dhh Initial
dhh authored
337 end
338
339 # Creates an object, instantly saves it as a record (if the validation permits it), and returns it. If the save
340 # fail under validations, the unsaved object is still returned.
341 def create(attributes = nil)
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#upd...
dhh authored
342 if attributes.is_a?(Array)
343 attributes.collect { |attr| create(attr) }
344 else
345 object = new(attributes)
346 object.save
347 object
348 end
db045db @dhh Initial
dhh authored
349 end
350
351 # Finds the record from the passed +id+, instantly saves it with the passed +attributes+ (if the validation permits it),
352 # and returns it. If the save fail under validations, the unsaved object is still returned.
353 def update(id, attributes)
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#upd...
dhh authored
354 if id.is_a?(Array)
355 idx = -1
356 id.collect { |id| idx += 1; update(id, attributes[idx]) }
357 else
358 object = find(id)
359 object.update_attributes(attributes)
360 object
361 end
db045db @dhh Initial
dhh authored
362 end
363
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#upd...
dhh authored
364 # Deletes the record with the given +id+ without instantiating an object first. If an array of ids is provided, all of them
365 # are deleted.
648b8fd @dhh Added Base.destroy and Base.delete to remove records without holding a r...
dhh authored
366 def delete(id)
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#upd...
dhh authored
367 delete_all([ "#{primary_key} IN (?)", id ])
648b8fd @dhh Added Base.destroy and Base.delete to remove records without holding a r...
dhh authored
368 end
369
370 # Destroys the record with the given +id+ by instantiating the object and calling #destroy (all the callbacks are the triggered).
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#upd...
dhh authored
371 # If an array of ids is provided, all of them are destroyed.
648b8fd @dhh Added Base.destroy and Base.delete to remove records without holding a r...
dhh authored
372 def destroy(id)
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#upd...
dhh authored
373 id.is_a?(Array) ? id.each { |id| destroy(id) } : find(id).destroy
648b8fd @dhh Added Base.destroy and Base.delete to remove records without holding a r...
dhh authored
374 end
375
69cb942 @dhh Changed the interface on AbstractAdapter to require that adapters return...
dhh authored
376 # Updates all records with the SET-part of an SQL update statement in +updates+ and returns an integer with the number of rows updates.
377 # A subset of the records can be selected by specifying +conditions+. Example:
db045db @dhh Initial
dhh authored
378 # Billing.update_all "category = 'authorized', approved = 1", "author = 'David'"
379 def update_all(updates, conditions = nil)
566a369 @dhh Added that update_all calls sanitize_sql on its updates argument, so stu...
dhh authored
380 sql = "UPDATE #{table_name} SET #{sanitize_sql(updates)} "
db045db @dhh Initial
dhh authored
381 add_conditions!(sql, conditions)
69cb942 @dhh Changed the interface on AbstractAdapter to require that adapters return...
dhh authored
382 return connection.update(sql, "#{name} Update")
db045db @dhh Initial
dhh authored
383 end
0d2db8a @dhh Added Base.update_collection that can update an array of id/attribute pa...
dhh authored
384
db045db @dhh Initial
dhh authored
385 # Destroys the objects for all the records that matches the +condition+ by instantiating each object and calling
386 # the destroy method. Example:
387 # Person.destroy_all "last_login < '2004-04-04'"
388 def destroy_all(conditions = nil)
389 find_all(conditions).each { |object| object.destroy }
390 end
391
392 # Deletes all the records that matches the +condition+ without instantiating the objects first (and hence not
393 # calling the destroy method). Example:
394 # Post.destroy_all "person_id = 5 AND (category = 'Something' OR category = 'Else')"
395 def delete_all(conditions = nil)
396 sql = "DELETE FROM #{table_name} "
397 add_conditions!(sql, conditions)
398 connection.delete(sql, "#{name} Delete all")
399 end
400
401 # Returns the number of records that meets the +conditions+. Zero is returned if no records match. Example:
402 # Product.count "sales > 1"
403 def count(conditions = nil)
404 sql = "SELECT COUNT(*) FROM #{table_name} "
405 add_conditions!(sql, conditions)
406 count_by_sql(sql)
407 end
408
409 # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
410 # Product.count "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
411 def count_by_sql(sql)
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in regu...
dhh authored
412 sql = sanitize_conditions(sql)
db045db @dhh Initial
dhh authored
413 count = connection.select_one(sql, "#{name} Count").values.first
414 return count ? count.to_i : 0
415 end
416
417 # Increments the specified counter by one. So <tt>DiscussionBoard.increment_counter("post_count",
418 # discussion_board_id)</tt> would increment the "post_count" counter on the board responding to discussion_board_id.
419 # This is used for caching aggregate values, so that they doesn't need to be computed every time. Especially important
420 # for looping over a collection where each element require a number of aggregate values. Like the DiscussionBoard
421 # that needs to list both the number of posts and comments.
422 def increment_counter(counter_name, id)
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers ar...
dhh authored
423 update_all "#{counter_name} = #{counter_name} + 1", "#{primary_key} = #{quote(id)}"
db045db @dhh Initial
dhh authored
424 end
425
426 # Works like increment_counter, but decrements instead.
427 def decrement_counter(counter_name, id)
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers ar...
dhh authored
428 update_all "#{counter_name} = #{counter_name} - 1", "#{primary_key} = #{quote(id)}"
db045db @dhh Initial
dhh authored
429 end
430
431 # Attributes named in this macro are protected from mass-assignment, such as <tt>new(attributes)</tt> and
432 # <tt>attributes=(attributes)</tt>. Their assignment will simply be ignored. Instead, you can use the direct writer
433 # methods to do assignment. This is meant to protect sensitive attributes to be overwritten by URL/form hackers. Example:
434 #
435 # class Customer < ActiveRecord::Base
436 # attr_protected :credit_rating
437 # end
438 #
439 # customer = Customer.new("name" => David, "credit_rating" => "Excellent")
440 # customer.credit_rating # => nil
441 # customer.attributes = { "description" => "Jolly fellow", "credit_rating" => "Superb" }
442 # customer.credit_rating # => nil
443 #
444 # customer.credit_rating = "Average"
445 # customer.credit_rating # => "Average"
446 def attr_protected(*attributes)
447 write_inheritable_array("attr_protected", attributes)
448 end
449
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
450 # Returns an array of all the attributes that have been protected from mass-assignment.
db045db @dhh Initial
dhh authored
451 def protected_attributes # :nodoc:
452 read_inheritable_attribute("attr_protected")
453 end
454
455 # If this macro is used, only those attributed named in it will be accessible for mass-assignment, such as
456 # <tt>new(attributes)</tt> and <tt>attributes=(attributes)</tt>. This is the more conservative choice for mass-assignment
457 # protection. If you'd rather start from an all-open default and restrict attributes as needed, have a look at
458 # attr_protected.
459 def attr_accessible(*attributes)
460 write_inheritable_array("attr_accessible", attributes)
461 end
462
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
463 # Returns an array of all the attributes that have been made accessible to mass-assignment.
db045db @dhh Initial
dhh authored
464 def accessible_attributes # :nodoc:
465 read_inheritable_attribute("attr_accessible")
466 end
467
468 # Specifies that the attribute by the name of +attr_name+ should be serialized before saving to the database and unserialized
469 # after loading from the database. The serialization is done through YAML. If +class_name+ is specified, the serialized
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
470 # object must be of that class on retrieval or +SerializationTypeMismatch+ will be raised.
db045db @dhh Initial
dhh authored
471 def serialize(attr_name, class_name = Object)
472 write_inheritable_attribute("attr_serialized", serialized_attributes.update(attr_name.to_s => class_name))
473 end
474
475 # Returns a hash of all the attributes that have been specified for serialization as keys and their class restriction as values.
476 def serialized_attributes
477 read_inheritable_attribute("attr_serialized") || { }
478 end
479
480 # Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending
481 # directly from ActiveRecord. So if the hierarchy looks like: Reply < Message < ActiveRecord, then Message is used
482 # to guess the table name from even when called on Reply. The guessing rules are as follows:
483 #
484 # * Class name ends in "x", "ch" or "ss": "es" is appended, so a Search class becomes a searches table.
485 # * Class name ends in "y" preceded by a consonant or "qu": The "y" is replaced with "ies", so a Category class becomes a categories table.
486 # * Class name ends in "fe": The "fe" is replaced with "ves", so a Wife class becomes a wives table.
487 # * Class name ends in "lf" or "rf": The "f" is replaced with "ves", so a Half class becomes a halves table.
488 # * Class name ends in "person": The "person" is replaced with "people", so a Salesperson class becomes a salespeople table.
489 # * Class name ends in "man": The "man" is replaced with "men", so a Spokesman class becomes a spokesmen table.
490 # * Class name ends in "sis": The "i" is replaced with an "e", so a Basis class becomes a bases table.
491 # * Class name ends in "tum" or "ium": The "um" is replaced with an "a", so a Datum class becomes a data table.
492 # * Class name ends in "child": The "child" is replaced with "children", so a NodeChild class becomes a node_children table.
493 # * Class name ends in an "s": No additional characters are added or removed.
494 # * Class name doesn't end in "s": An "s" is appended, so a Comment class becomes a comments table.
495 # * Class name with word compositions: Compositions are underscored, so CreditCard class becomes a credit_cards table.
496 #
497 # Additionally, the class-level table_name_prefix is prepended to the table_name and the table_name_suffix is appended.
498 # So if you have "myapp_" as a prefix, the table name guess for an Account class becomes "myapp_accounts".
499 #
500 # You can also overwrite this class method to allow for unguessable links, such as a Mouse class with a link to a
501 # "mice" table. Example:
502 #
503 # class Mouse < ActiveRecord::Base
504 # def self.table_name() "mice" end
505 # end
dcc4868 @dhh Fixed that Base.table_name would expect a parameter when used in has_and...
dhh authored
506 def table_name
507 table_name_prefix + undecorated_table_name(class_name_of_active_record_descendant(self)) + table_name_suffix
db045db @dhh Initial
dhh authored
508 end
509
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
510 # Defines the primary key field -- can be overridden in subclasses. Overwriting will negate any effect of the
db045db @dhh Initial
dhh authored
511 # primary_key_prefix_type setting, though.
512 def primary_key
513 case primary_key_prefix_type
514 when :table_name
515 Inflector.foreign_key(class_name_of_active_record_descendant(self), false)
516 when :table_name_with_underscore
517 Inflector.foreign_key(class_name_of_active_record_descendant(self))
518 else
519 "id"
520 end
521 end
522
523 # Defines the column name for use with single table inheritance -- can be overridden in subclasses.
524 def inheritance_column
525 "type"
526 end
527
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindings ...
dhh authored
528 # Defines an "attribute" method (like #inheritance_column or
529 # #table_name). A new (class) method will be created with the
530 # given name. If a value is specified, the new method will
531 # return that value (as a string). Otherwise, the given block
532 # will be used to compute the value of the method.
533 #
534 # The original method will be aliased, with the new name being
535 # prefixed with "original_". This allows the new method to
536 # access the original value.
537 #
538 # Example:
539 #
540 # class A < ActiveRecord::Base
541 # define_attr_method :primary_key, "sysid"
542 # define_attr_method( :inheritance_column ) do
543 # original_inheritance_column + "_id"
544 # end
545 # end
546 def define_attr_method( name, value=nil, &block )
547 sing = class << self; self; end
548 block = proc { value.to_s } if value
549 sing.send( :alias_method, "original_#{name}", name )
550 sing.send( :define_method, name, &block )
551 end
552
553 # Sets the table name to use to the given value, or (if the value
554 # is nil or false) to the value returned by the given block. (See
555 # #define_attr_method).
556 #
557 # Example:
558 #
559 # class Project < ActiveRecord::Base
560 # set_table_name "project"
561 # end
562 def set_table_name( value=nil, &block )
563 define_attr_method :table_name, value, &block
564 end
565 alias :table_name= :set_table_name
566
567 # Sets the name of the primary key column to use to the given value,
568 # or (if the value is nil or false) to the value returned by the given
569 # block. (See #define_attr_method).
570 #
571 # Example:
572 #
573 # class Project < ActiveRecord::Base
574 # set_primary_key "sysid"
575 # end
576 def set_primary_key( value=nil, &block )
577 define_attr_method :primary_key, value, &block
578 end
579 alias :primary_key= :set_primary_key
580
581 # Sets the name of the inheritance column to use to the given value,
582 # or (if the value # is nil or false) to the value returned by the
583 # given block. (See # #define_attr_method).
584 #
585 # Example:
586 #
587 # class Project < ActiveRecord::Base
588 # set_inheritance_column do
589 # original_inheritance_column + "_id"
590 # end
591 # end
592 def set_inheritance_column( value=nil, &block )
593 define_attr_method :inheritance_column, value, &block
594 end
595 alias :inheritance_column= :set_inheritance_column
596
db045db @dhh Initial
dhh authored
597 # Turns the +table_name+ back into a class name following the reverse rules of +table_name+.
598 def class_name(table_name = table_name) # :nodoc:
599 # remove any prefix and/or suffix from the table name
600 class_name = Inflector.camelize(table_name[table_name_prefix.length..-(table_name_suffix.length + 1)])
601 class_name = Inflector.singularize(class_name) if pluralize_table_names
602 return class_name
603 end
604
605 # Returns an array of column objects for the table associated with this class.
606 def columns
607 @columns ||= connection.columns(table_name, "#{name} Columns")
608 end
609
610 # Returns an array of column objects for the table associated with this class.
611 def columns_hash
612 @columns_hash ||= columns.inject({}) { |hash, column| hash[column.name] = column; hash }
613 end
614
615 # Returns an array of columns objects where the primary id, all columns ending in "_id" or "_count",
616 # and columns used for single table inheritance has been removed.
617 def content_columns
618 @content_columns ||= columns.reject { |c| c.name == primary_key || c.name =~ /(_id|_count)$/ || c.name == inheritance_column }
619 end
620
621 # 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
622 # 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
623 # is available.
624 def column_methods_hash
625 @dynamic_methods_hash ||= columns_hash.keys.inject(Hash.new(false)) do |methods, attr|
626 methods[attr.to_sym] = true
627 methods["#{attr}=".to_sym] = true
628 methods["#{attr}?".to_sym] = true
dad37cf @dhh FormHelper should only use *_before_type_cast if they available on the m...
dhh authored
629 methods["#{attr}_before_type_cast".to_sym] = true
db045db @dhh Initial
dhh authored
630 methods
631 end
632 end
1314f48 @dhh Added methods for resetting the cached information on classes that you w...
dhh authored
633
634 # Resets all the cached information about columns, which will cause they to be reloaded on the next request.
635 def reset_column_information
636 @columns = @columns_hash = @content_columns = @dynamic_methods_hash = nil
637 end
638
639 def reset_column_information_and_inheritable_attributes_for_all_subclasses
640 subclasses.each { |klass| klass.reset_inheritable_attributes; klass.reset_column_information }
641 end
db045db @dhh Initial
dhh authored
642
643 # Transforms attribute key names into a more humane format, such as "First name" instead of "first_name". Example:
644 # Person.human_attribute_name("first_name") # => "First name"
645 def human_attribute_name(attribute_key_name)
1f7e72f @dhh Made human_attribute_name(attribute_key_name) use Inflector.humanize
dhh authored
646 attribute_key_name.humanize
db045db @dhh Initial
dhh authored
647 end
648
649 def descends_from_active_record? # :nodoc:
605bc77 @dhh Added a better exception for when a type column is used in a table witho...
dhh authored
650 superclass == Base || !columns_hash.has_key?(inheritance_column)
db045db @dhh Initial
dhh authored
651 end
652
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers ar...
dhh authored
653 def quote(object)
654 connection.quote(object)
655 end
656
657 # Used to sanitize objects before they're used in an SELECT SQL-statement. Delegates to <tt>connection.quote</tt>.
db045db @dhh Initial
dhh authored
658 def sanitize(object) # :nodoc:
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers ar...
dhh authored
659 connection.quote(object)
db045db @dhh Initial
dhh authored
660 end
661
662 # Used to aggregate logging and benchmark, so you can measure and represent multiple statements in a single block.
663 # Usage (hides all the SQL calls for the individual actions and calculates total runtime for them all):
664 #
665 # Project.benchmark("Creating project") do
666 # project = Project.create("name" => "stuff")
667 # project.create_manager("name" => "David")
668 # project.milestones << Milestone.find_all
669 # end
670 def benchmark(title)
671 result = nil
c00bf5f @dhh Fixed the verbosity of using the AR store
dhh authored
672 bm = Benchmark.measure { result = silence { yield } }
673 logger.info "#{title} (#{sprintf("%f", bm.real)})"
674 return result
675 end
676
677 # Silences the logger for the duration of the block.
678 def silence
679 result = nil
db045db @dhh Initial
dhh authored
680 logger.level = Logger::ERROR
c00bf5f @dhh Fixed the verbosity of using the AR store
dhh authored
681 result = yield
db045db @dhh Initial
dhh authored
682 logger.level = Logger::DEBUG
683 return result
684 end
685
97849de @dhh Fixed that association proxies would fail === tests like PremiumSubscrip...
dhh authored
686 # Overwrite the default class equality method to provide support for association proxies.
687 def ===(object)
688 object.is_a?(self)
689 end
690
db045db @dhh Initial
dhh authored
691 private
692 # Finder methods must instantiate through this method to work with the single-table inheritance model
693 # that makes it possible to create objects of different types from the same table.
694 def instantiate(record)
605bc77 @dhh Added a better exception for when a type column is used in a table witho...
dhh authored
695 require_association_class(record[inheritance_column])
696
697 begin
698 object = record_with_type?(record) ? compute_type(record[inheritance_column]).allocate : allocate
699 rescue NameError
700 raise(
701 SubclassNotFound,
702 "The single-table inheritance mechanism failed to locate the subclass: '#{record[inheritance_column]}'. " +
703 "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " +
704 "Please rename this column if you didn't intend it to be used for storing the inheritance class " +
705 "or overwrite #{self.to_s}.inheritance_column to use another column for that information."
706 )
707 end
708
db045db @dhh Initial
dhh authored
709 object.instance_variable_set("@attributes", record)
710 return object
711 end
712
713 # Returns true if the +record+ has a single table inheritance column and is using it.
714 def record_with_type?(record)
715 record.include?(inheritance_column) && !record[inheritance_column].nil? &&
716 !record[inheritance_column].empty?
717 end
718
719 # Returns the name of the type of the record using the current module as a prefix. So descendents of
720 # MyApp::Business::Account would be appear as "MyApp::Business::AccountSubclass".
721 def type_name_with_module(type_name)
722 self.name =~ /::/ ? self.name.scan(/(.*)::/).first.first + "::" + type_name : type_name
723 end
724
725 # Adds a sanitized version of +conditions+ to the +sql+ string. Note that it's the passed +sql+ string is changed.
726 def add_conditions!(sql, conditions)
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
727 sql << "WHERE #{sanitize_sql(conditions)} " unless conditions.nil?
db045db @dhh Initial
dhh authored
728 sql << (conditions.nil? ? "WHERE " : " AND ") + type_condition unless descends_from_active_record?
729 end
730
731 def type_condition
732 " (" + subclasses.inject("#{inheritance_column} = '#{Inflector.demodulize(name)}' ") do |condition, subclass|
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers ar...
dhh authored
733 condition << "OR #{inheritance_column} = '#{Inflector.demodulize(subclass.name)}' "
db045db @dhh Initial
dhh authored
734 end + ") "
735 end
736
737 # Guesses the table name, but does not decorate it with prefix and suffix information.
738 def undecorated_table_name(class_name = class_name_of_active_record_descendant(self))
739 table_name = Inflector.underscore(Inflector.demodulize(class_name))
740 table_name = Inflector.pluralize(table_name) if pluralize_table_names
741 return table_name
742 end
743
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting object...
dhh authored
744 # Enables dynamic finders like find_by_user_name(user_name) and find_by_user_name_and_password(user_name, password) that are turned into
959f362 @dhh Added find_all style to the new dynamic finders
dhh authored
745 # find_first(["user_name = ?", user_name]) and find_first(["user_name = ? AND password = ?", user_name, password]) respectively. Also works
746 # for find_all, but using find_all_by_amount(50) that are turned into find_all(["amount = ?", 50]).
569f2ea @dhh Added the possibility of specifying the remaining options for find_first...
dhh authored
747 #
748 # It's even possible to use all the additional parameters to find_first and find_all. For example, the full interface for find_all_by_amount
749 # is actually find_all_by_amount(amount, orderings = nil, limit = nil, joins = nil).
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting object...
dhh authored
750 def method_missing(method_id, *arguments)
751 method_name = method_id.id2name
752
959f362 @dhh Added find_all style to the new dynamic finders
dhh authored
753 if method_name =~ /find_(all_by|by)_([_a-z]+)/
754 finder, attributes = ($1 == "all_by" ? :find_all : :find_first), $2.split("_and_")
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting object...
dhh authored
755 attributes.each { |attr_name| super unless column_methods_hash[attr_name.intern] }
93ec130 @dhh Fixed that the dynamic finders didnt treat nil as a "IS NULL" but rather...
dhh authored
756
757 attr_index = -1
28edbca @dhh Fixed that the dynamic finder like find_all_by_something_boolean(false) ...
dhh authored
758 conditions = attributes.collect { |attr_name| attr_index += 1; "#{attr_name} #{arguments[attr_index].nil? ? "IS" : "="} ? " }.join(" AND ")
569f2ea @dhh Added the possibility of specifying the remaining options for find_first...
dhh authored
759 send(finder, [conditions, *arguments[0...attributes.length]], *arguments[attributes.length..-1])
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting object...
dhh authored
760 else
761 super
762 end
763 end
db045db @dhh Initial
dhh authored
764
765 protected
766 def subclasses
767 @@subclasses[self] ||= []
768 @@subclasses[self] + extra = @@subclasses[self].inject([]) {|list, subclass| list + subclass.subclasses }
769 end
770
771 # Returns the class type of the record using the current module as a prefix. So descendents of
772 # MyApp::Business::Account would be appear as MyApp::Business::AccountSubclass.
773 def compute_type(type_name)
774 type_name_with_module(type_name).split("::").inject(Object) do |final_type, part|
775 final_type = final_type.const_get(part)
776 end
777 end
778
779 # Returns the name of the class descending directly from ActiveRecord in the inheritance hierarchy.
780 def class_name_of_active_record_descendant(klass)
781 if klass.superclass == Base
782 return klass.name
783 elsif klass.superclass.nil?
784 raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord"
785 else
786 class_name_of_active_record_descendant(klass.superclass)
787 end
788 end
789
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
790 # Accepts an array or string. The string is returned untouched, but the array has each value
791 # sanitized and interpolated into the sql statement.
792 # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
793 def sanitize_sql(ary)
794 return ary unless ary.is_a?(Array)
3e7d191 @dhh Added bind-style variable interpolation for the condition arrays that us...
dhh authored
795
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
796 statement, *values = ary
797 if values.first.is_a?(Hash) and statement =~ /:\w+/
798 replace_named_bind_variables(statement, values.first)
799 elsif statement.include?('?')
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
800 replace_bind_variables(statement, values)
801 else
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers ar...
dhh authored
802 statement % values.collect { |value| connection.quote_string(value.to_s) }
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
803 end
3e7d191 @dhh Added bind-style variable interpolation for the condition arrays that us...
dhh authored
804 end
805
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
806 alias_method :sanitize_conditions, :sanitize_sql
807
3e7d191 @dhh Added bind-style variable interpolation for the condition arrays that us...
dhh authored
808 def replace_bind_variables(statement, values)
9322168 @dhh Restored bind arity checking #412 [bitsweat]
dhh authored
809 raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size)
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
810 bound = values.dup
872ddaf @dhh Added bind-named arrays for interpolating a group of ids or strings in c...
dhh authored
811 statement.gsub('?') { quote_bound_value(bound.shift) }
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
812 end
813
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
814 def replace_named_bind_variables(statement, bind_vars)
9322168 @dhh Restored bind arity checking #412 [bitsweat]
dhh authored
815 raise_if_bind_arity_mismatch(statement, statement.scan(/:(\w+)/).uniq.size, bind_vars.size)
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
816 statement.gsub(/:(\w+)/) do
817 match = $1.to_sym
818 if bind_vars.has_key?(match)
872ddaf @dhh Added bind-named arrays for interpolating a group of ids or strings in c...
dhh authored
819 quote_bound_value(bind_vars[match])
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
820 else
821 raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}"
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
822 end
823 end
9322168 @dhh Restored bind arity checking #412 [bitsweat]
dhh authored
824 end
825
872ddaf @dhh Added bind-named arrays for interpolating a group of ids or strings in c...
dhh authored
826 def quote_bound_value(value)
827 case value
828 when Array
829 value.map { |v| connection.quote(v) }.join(',')
830 else
831 connection.quote(value)
832 end
833 end
834
9322168 @dhh Restored bind arity checking #412 [bitsweat]
dhh authored
835 def raise_if_bind_arity_mismatch(statement, expected, provided)
836 unless expected == provided
837 raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}"
838 end
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
839 end
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
840
6bd672e @dhh Added that Base#find takes an optional options hash, including :conditio...
dhh authored
841 def extract_options_from_args!(args)
842 if args.last.is_a?(Hash) then args.pop else {} end
db045db @dhh Initial
dhh authored
843 end
aaf9a45 @dhh Added Base.validate_uniqueness thatv alidates whether the value of the s...
dhh authored
844
845 def encode_quoted_value(value)
846 quoted_value = connection.quote(value)
847 quoted_value = "'#{quoted_value[1..-2].gsub(/\'/, "\\\\'")}'" if quoted_value.include?("\\\'")
848 quoted_value
849 end
db045db @dhh Initial
dhh authored
850 end
851
852 public
853 # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
854 # attributes but not yet saved (pass a hash with key names matching the associated table column names).
855 # In both instances, valid attribute keys are determined by the column names of the associated table --
856 # hence you can't have attributes that aren't part of the table columns.
857 def initialize(attributes = nil)
858 @attributes = attributes_from_column_definition
859 @new_record = true
860 ensure_proper_type
861 self.attributes = attributes unless attributes.nil?
862 yield self if block_given?
863 end
864
865 # Every Active Record class must use "id" as their primary ID. This getter overwrites the native
866 # id method, which isn't being used in this context.
867 def id
868 read_attribute(self.class.primary_key)
869 end
870
3e5a880 @dhh Switched strategy on the id_before_type_cast problem and just did an exp...
dhh authored
871 def id_before_type_cast
872 read_attribute_before_type_cast(self.class.primary_key)
873 end
874
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers ar...
dhh authored
875 def quoted_id
876 quote(id, self.class.columns_hash[self.class.primary_key])
877 end
878
db045db @dhh Initial
dhh authored
879 # Sets the primary ID.
880 def id=(value)
881 write_attribute(self.class.primary_key, value)
882 end
883
884 # Returns true if this object hasn't been saved yet -- that is, a record for the object doesn't exist yet.
885 def new_record?
886 @new_record
887 end
888
889 # * No record exists: Creates a new record with values matching those of the object attributes.
890 # * A record does exist: Updates the record with values matching those of the object attributes.
891 def save
892 create_or_update
893 end
894
895 # Deletes the record in the database and freezes this instance to reflect that no changes should
896 # be made (since they can't be persisted).
897 def destroy
898 unless new_record?
899 connection.delete(
900 "DELETE FROM #{self.class.table_name} " +
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers ar...
dhh authored
901 "WHERE #{self.class.primary_key} = #{quote(id)}",
db045db @dhh Initial
dhh authored
902 "#{self.class.name} Destroy"
903 )
904 end
905
906 freeze
907 end
908
909 # Returns a clone of the record that hasn't been assigned an id yet and is treated as a new record.
910 def clone
431e21c @dhh Fixed Base#clone for use with PostgreSQL #565 [hanson@surgery.wisc.edu]
dhh authored
911 attrs = self.attributes
a3298e5 @dhh Small indent
dhh authored
912 attrs.delete(self.class.primary_key)
431e21c @dhh Fixed Base#clone for use with PostgreSQL #565 [hanson@surgery.wisc.edu]
dhh authored
913 cloned_record = self.class.new(attrs)
db045db @dhh Initial
dhh authored
914 cloned_record
915 end
916
917 # Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records.
d678997 @dhh Base#update_attribute isnt subject to validation
dhh authored
918 # Note: This method is overwritten by the Validation module that'll make sure that updates made with this method
919 # doesn't get subjected to validation checks. Hence, attributes can be updated even if the full object isn't valid.
db045db @dhh Initial
dhh authored
920 def update_attribute(name, value)
393e98a @dhh Fixed Base#update_attribute to be indifferent to whether a string or sym...
dhh authored
921 self[name] = value
d1abe80 @dhh Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it e...
dhh authored
922 save
604a094 @dhh Added Base#update_attributes that'll accept a hash of attributes and sav...
dhh authored
923 end
924
d678997 @dhh Base#update_attribute isnt subject to validation
dhh authored
925 # Updates all the attributes in from the passed hash and saves the record. If the object is invalid, the saving will
926 # fail and false will be returned.
604a094 @dhh Added Base#update_attributes that'll accept a hash of attributes and sav...
dhh authored
927 def update_attributes(attributes)
3bef4c2 @dhh Made Base#update_attributes actually work
dhh authored
928 self.attributes = attributes
604a094 @dhh Added Base#update_attributes that'll accept a hash of attributes and sav...
dhh authored
929 return save
db045db @dhh Initial
dhh authored
930 end
931
d1abe80 @dhh Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it e...
dhh authored
932 # Initializes the +attribute+ to zero if nil and adds one. Only makes sense for number-based attributes. Returns self.
933 def increment(attribute)
934 self[attribute] ||= 0
935 self[attribute] += 1
936 self
937 end
938
939 # Increments the +attribute+ and saves the record.
940 def increment!(attribute)
941 increment(attribute).update_attribute(attribute, self[attribute])
942 end
943
944 # Initializes the +attribute+ to zero if nil and subtracts one. Only makes sense for number-based attributes. Returns self.
945 def decrement(attribute)
946 self[attribute] ||= 0
947 self[attribute] -= 1
948 self
949 end
950
951 # Decrements the +attribute+ and saves the record.
952 def decrement!(attribute)
953 decrement(attribute).update_attribute(attribute, self[attribute])
954 end
955
956 # Turns an +attribute+ that's currently true into false and vice versa. Returns self.
957 def toggle(attribute)
958 self[attribute] = quote(!send("#{attribute}?", column_for_attribute(attribute)))
959 self
960 end
961
962 # Toggles the +attribute+ and saves the record.
963 def toggle!(attribute)
964 toggle(attribute).update_attribute(attribute, self[attribute])
965 end
966
3ff5c58 @dhh Added Base#reload that reloads the attributes of an object from the data...
dhh authored
967 # Reloads the attributes of this object from the database.
968 def reload
969 clear_association_cache
970 @attributes.update(self.class.find(self.id).instance_variable_get('@attributes'))
971 return self
972 end
973
db045db @dhh Initial
dhh authored
974 # Returns the value of attribute identified by <tt>attr_name</tt> after it has been type cast (for example,
975 # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
976 # (Alias for the protected read_attribute method).
977 def [](attr_name)
d1abe80 @dhh Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it e...
dhh authored
978 read_attribute(attr_name.to_s)
db045db @dhh Initial
dhh authored
979 end
980
981 # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
982 # (Alias for the protected write_attribute method).
983 def []= (attr_name, value)
d1abe80 @dhh Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it e...
dhh authored
984 write_attribute(attr_name.to_s, value)
db045db @dhh Initial
dhh authored
985 end
986
987 # Allows you to set all the attributes at once by passing in a hash with keys
988 # matching the attribute names (which again matches the column names). Sensitive attributes can be protected
989 # from this form of mass-assignment by using the +attr_protected+ macro. Or you can alternatively
990 # specify which attributes *can* be accessed in with the +attr_accessible+ macro. Then all the
991 # attributes not included in that won't be allowed to be mass-assigned.
992 def attributes=(attributes)
993 return if attributes.nil?
994
995 multi_parameter_attributes = []
996 remove_attributes_protected_from_mass_assignment(attributes).each do |k, v|
997 k.include?("(") ? multi_parameter_attributes << [ k, v ] : send(k + "=", v)
998 end
999 assign_multiparameter_attributes(multi_parameter_attributes)
1000 end
1001
b067bf7 @dhh Added Base#attributes that returns a hash of all the attributes with the...
dhh authored
1002 # Returns a hash of all the attributes with their names as keys and clones of their objects as values.
1003 def attributes
1004 self.attribute_names.inject({}) do |attributes, name|
1005 begin
1006 attributes[name] = read_attribute(name).clone
1007 rescue TypeError
1008 attributes[name] = read_attribute(name)
1009 end
1010 attributes
1011 end
1012 end
1013
db045db @dhh Initial
dhh authored
1014 # Returns true if the specified +attribute+ has been set by the user or by a database load and is neither
1015 # nil nor empty? (the latter only applies to objects that responds to empty?, most notably Strings).
1016 def attribute_present?(attribute)
1017 is_empty = read_attribute(attribute).respond_to?("empty?") ? read_attribute(attribute).empty? : false
1018 @attributes.include?(attribute) && !@attributes[attribute].nil? && !is_empty
1019 end
1020
1021 # Returns an array of names for the attributes available on this object sorted alphabetically.
1022 def attribute_names
1023 @attributes.keys.sort
1024 end
1025
1026 # Returns the column object for the named attribute.
1027 def column_for_attribute(name)
d1abe80 @dhh Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it e...
dhh authored
1028 self.class.columns_hash[name.to_s]
db045db @dhh Initial
dhh authored
1029 end
1030
823554e @dhh Added support for associating unsaved objects #402 [Tim Bates]
dhh authored
1031 # Returns true if the +comparison_object+ is the same object, or is of the same type and has the same id.
db045db @dhh Initial
dhh authored
1032 def ==(comparison_object)
823554e @dhh Added support for associating unsaved objects #402 [Tim Bates]
dhh authored
1033 comparison_object.equal?(self) or (comparison_object.instance_of?(self.class) and comparison_object.id == id)
db045db @dhh Initial
dhh authored
1034 end
1035
1036 # Delegates to ==
1037 def eql?(comparison_object)
1038 self == (comparison_object)
1039 end
1040
1041 # Delegates to id in order to allow two records of the same type and id to work with something like:
1042 # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
1043 def hash
1044 id
1045 end
1046
1047 # For checking respond_to? without searching the attributes (which is faster).
1048 alias_method :respond_to_without_attributes?, :respond_to?
1049
1050 # A Person object with a name attribute can ask person.respond_to?("name"), person.respond_to?("name="), and
1051 # person.respond_to?("name?") which will all return true.
846f0d5 @dhh Fixed that the overwritten respond_to? method didn't take two parameters...
dhh authored
1052 def respond_to?(method, include_priv = false)
1053 self.class.column_methods_hash[method.to_sym] || respond_to_without_attributes?(method, include_priv)
db045db @dhh Initial
dhh authored
1054 end
d82f73e @dhh Abolished ActionController::Base.require_or_load in favor of require_dep...
dhh authored
1055
db045db @dhh Initial
dhh authored
1056 private
1057 def create_or_update
1058 if new_record? then create else update end
823554e @dhh Added support for associating unsaved objects #402 [Tim Bates]
dhh authored
1059 return true
db045db @dhh Initial
dhh authored
1060 end
1061
1062 # Updates the associated record with values matching those of the instant attributes.
1063 def update
1064 connection.update(
1065 "UPDATE #{self.class.table_name} " +
9a248a8 @dhh Dont include the primary key in updates -- its unneeded and SQL Server c...
dhh authored
1066 "SET #{quoted_comma_pair_list(connection, attributes_with_quotes(false))} " +
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers ar...
dhh authored
1067 "WHERE #{self.class.primary_key} = #{quote(id)}",
db045db @dhh Initial
dhh authored
1068 "#{self.class.name} Update"
1069 )
1070 end
1071
1072 # Creates a new record with values matching those of the instant attributes.
1073 def create
1074 self.id = connection.insert(
1075 "INSERT INTO #{self.class.table_name} " +
1076 "(#{quoted_column_names.join(', ')}) " +
1077 "VALUES(#{attributes_with_quotes.values.join(', ')})",
1078 "#{self.class.name} Create",
1079 self.class.primary_key, self.id
1080 )
1081
1082 @new_record = false
1083 end
1084
1085 # Sets the attribute used for single table inheritance to this class name if this is not the ActiveRecord descendant.
1086 # Considering the hierarchy Reply < Message < ActiveRecord, this makes it possible to do Reply.new without having to
1087 # set Reply[Reply.inheritance_column] = "Reply" yourself. No such attribute would be set for objects of the
1088 # Message class in that example.
1089 def ensure_proper_type
1090 unless self.class.descends_from_active_record?
1091 write_attribute(self.class.inheritance_column, Inflector.demodulize(self.class.name))
1092 end
1093 end
1094
1095 # Allows access to the object attributes, which are held in the @attributes hash, as were
1096 # they first-class methods. So a Person class with a name attribute can use Person#name and
1097 # Person#name= and never directly use the attributes hash -- except for multiple assigns with
1098 # ActiveRecord#attributes=. A Milestone class can also ask Milestone#completed? to test that
1099 # the completed attribute is not nil or 0.
1100 #
1101 # It's also possible to instantiate related objects, so a Client class belonging to the clients
1102 # table with a master_id foreign key can instantiate master through Client#master.
1103 def method_missing(method_id, *arguments)
1104 method_name = method_id.id2name
daf3e92 @dhh Added a db2 adapter that only depends on the Ruby/DB2 bindings (http://r...
dhh authored
1105
db045db @dhh Initial
dhh authored
1106 if method_name =~ read_method? && @attributes.include?($1)
1107 return read_attribute($1)
7b5ed66 @dhh Added respondence to *_before_type_cast for all attributes to return the...
dhh authored
1108 elsif method_name =~ read_untyped_method? && @attributes.include?($1)
1109 return read_attribute_before_type_cast($1)
db045db @dhh Initial
dhh authored
1110 elsif method_name =~ write_method? && @attributes.include?($1)
1111 write_attribute($1, arguments[0])
1112 elsif method_name =~ query_method? && @attributes.include?($1)
1113 return query_attribute($1)
1114 else
1115 super
1116 end
1117 end
1118
7b5ed66 @dhh Added respondence to *_before_type_cast for all attributes to return the...
dhh authored
1119 def read_method?() /^([a-zA-Z][-_\w]*)[^=?]*$/ end
1120 def read_untyped_method?() /^([a-zA-Z][-_\w]*)_before_type_cast$/ end
1121 def write_method?() /^([a-zA-Z][-_\w]*)=.*$/ end
1122 def query_method?() /^([a-zA-Z][-_\w]*)\?$/ end
db045db @dhh Initial
dhh authored
1123
7b5ed66 @dhh Added respondence to *_before_type_cast for all attributes to return the...
dhh authored
1124 # Returns the value of attribute identified by <tt>attr_name</tt> after it has been type cast (for example,
db045db @dhh Initial
dhh authored
1125 # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
1126 def read_attribute(attr_name) #:doc:
1127 if @attributes.keys.include? attr_name
1128 if column = column_for_attribute(attr_name)
7b5ed66 @dhh Added respondence to *_before_type_cast for all attributes to return the...
dhh authored
1129 unserializable_attribute?(attr_name, column) ?
db045db @dhh Initial
dhh authored
1130 unserialize_attribute(attr_name) : column.type_cast(@attributes[attr_name])
7b5ed66 @dhh Added respondence to *_before_type_cast for all attributes to return the...
dhh authored
1131 else
1132 @attributes[attr_name]
db045db @dhh Initial
dhh authored
1133 end
1134 else
1135 nil
1136 end
1137 end
1138
7b5ed66 @dhh Added respondence to *_before_type_cast for all attributes to return the...
dhh authored
1139 def read_attribute_before_type_cast(attr_name)
1140 @attributes[attr_name]
1141 end
1142
db045db @dhh Initial
dhh authored
1143 # Returns true if the attribute is of a text column and marked for serialization.
1144 def unserializable_attribute?(attr_name, column)
daf3e92 @dhh Added a db2 adapter that only depends on the Ruby/DB2 bindings (http://r...
dhh authored
1145 @attributes[attr_name] && [:text, :string].include?(column.send(:type)) && @attributes[attr_name].is_a?(String) && self.class.serialized_attributes[attr_name]
db045db @dhh Initial
dhh authored
1146 end
1147
1148 # Returns the unserialized object of the attribute.
1149 def unserialize_attribute(attr_name)
1150 unserialized_object = object_from_yaml(@attributes[attr_name])
1151
1152 if unserialized_object.is_a?(self.class.serialized_attributes[attr_name])
1153 @attributes[attr_name] = unserialized_object
1154 else
1155 raise(
1156 SerializationTypeMismatch,
1157 "#{attr_name} was supposed to be a #{self.class.serialized_attributes[attr_name]}, " +
1158 "but was a #{unserialized_object.class.to_s}"
1159 )
1160 end
1161 end
1162
1163 # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+. Empty strings for fixnum and float
1164 # columns are turned into nil.
1165 def write_attribute(attr_name, value) #:doc:
1166 @attributes[attr_name] = empty_string_for_number_column?(attr_name, value) ? nil : value
1167 end
1168
1169 def empty_string_for_number_column?(attr_name, value)
1170 column = column_for_attribute(attr_name)
1171 column && (column.klass == Fixnum || column.klass == Float) && value == ""
1172 end
1173
1174 def query_attribute(attr_name)
1175 attribute = @attributes[attr_name]
1176 if attribute.kind_of?(Fixnum) && attribute == 0
1177 false
1178 elsif attribute.kind_of?(String) && attribute == "0"
1179 false
1180 elsif attribute.kind_of?(String) && attribute.empty?
1181 false
1182 elsif attribute.nil?
1183 false
1184 elsif attribute == false
1185 false
1186 elsif attribute == "f"
1187 false
1188 elsif attribute == "false"
1189 false
1190 else
1191 true
1192 end
1193 end
1194
1195 def remove_attributes_protected_from_mass_assignment(attributes)
1196 if self.class.accessible_attributes.nil? && self.class.protected_attributes.nil?
95454bf @dhh Added mass-assignment protection for the inheritance column -- regardles...
dhh authored
1197 attributes.reject { |key, value| attributes_protected_by_default.include?(key) }
db045db @dhh Initial
dhh authored
1198 elsif self.class.protected_attributes.nil?
95454bf @dhh Added mass-assignment protection for the inheritance column -- regardles...
dhh authored
1199 attributes.reject { |key, value| !self.class.accessible_attributes.include?(key.intern) || attributes_protected_by_default.include?(key) }
db045db @dhh Initial
dhh authored
1200 elsif self.class.accessible_attributes.nil?
95454bf @dhh Added mass-assignment protection for the inheritance column -- regardles...
dhh authored
1201 attributes.reject { |key, value| self.class.protected_attributes.include?(key.intern) || attributes_protected_by_default.include?(key) }
db045db @dhh Initial
dhh authored
1202 end
1203 end
1204
95454bf @dhh Added mass-assignment protection for the inheritance column -- regardles...
dhh authored
1205 # The primary key and inheritance column can never be set by mass-assignment for security reasons.
1206 def attributes_protected_by_default
1207 [ self.class.primary_key, self.class.inheritance_column ]
1208 end
1209
db045db @dhh Initial
dhh authored
1210 # Returns copy of the attributes hash where all the values have been safely quoted for use in
1211 # an SQL statement.
9a248a8 @dhh Dont include the primary key in updates -- its unneeded and SQL Server c...
dhh authored
1212 def attributes_with_quotes(include_primary_key = true)
db045db @dhh Initial
dhh authored
1213 columns_hash = self.class.columns_hash
b29c01e @dhh Added that has_and_belongs_to_many associations with additional attribut...
dhh authored
1214
1d61845 @dhh Fixed that records fetched with piggy-back attributes or through rich ha...
dhh authored
1215 attrs_quoted = @attributes.inject({}) do |attrs_quoted, pair|
9a248a8 @dhh Dont include the primary key in updates -- its unneeded and SQL Server c...
dhh authored
1216 attrs_quoted[pair.first] = quote(pair.last, columns_hash[pair.first]) unless !include_primary_key && pair.first == self.class.primary_key
db045db @dhh Initial
dhh authored
1217 attrs_quoted
1218 end
b29c01e @dhh Added that has_and_belongs_to_many associations with additional attribut...
dhh authored
1219
1220 attrs_quoted.delete_if { |key, value| !self.class.columns_hash.keys.include?(key) }
db045db @dhh Initial
dhh authored
1221 end
1222
1223 # Quote strings appropriately for SQL statements.
1224 def quote(value, column = nil)
1225 connection.quote(value, column)
1226 end
1227
1228 # Interpolate custom sql string in instance context.
1229 # Optional record argument is meant for custom insert_sql.
1230 def interpolate_sql(sql, record = nil)
1231 instance_eval("%(#{sql})")
1232 end
1233
1234 # Initializes the attributes array with keys matching the columns from the linked table and
1235 # the values matching the corresponding default value of that column, so
1236 # that a new instance, or one populated from a passed-in Hash, still has all the attributes
1237 # that instances loaded from the database would.
1238 def attributes_from_column_definition
1239 connection.columns(self.class.table_name, "#{self.class.name} Columns").inject({}) do |attributes, column|
3e5a880 @dhh Switched strategy on the id_before_type_cast problem and just did an exp...
dhh authored
1240 attributes[column.name] = column.default unless column.name == self.class.primary_key
db045db @dhh Initial
dhh authored
1241 attributes
1242 end
1243 end
1244
1245 # Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done
1246 # by calling new on the column type or aggregation type (through composed_of) object with these parameters.
1247 # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
1248 # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
1249 # parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, f for Float,
db045db @dhh Initial
dhh authored
1250 # s for String, and a for Array. If all the values for a given attribute is empty, the attribute will be set to nil.
1251 def assign_multiparameter_attributes(pairs)
1252 execute_callstack_for_multiparameter_attributes(
1253 extract_callstack_for_multiparameter_attributes(pairs)
1254 )
1255 end
1256
1257 # Includes an ugly hack for Time.local instead of Time.new because the latter is reserved by Time itself.
1258 def execute_callstack_for_multiparameter_attributes(callstack)
1259 callstack.each do |name, values|
1260 klass = (self.class.reflect_on_aggregation(name) || column_for_attribute(name)).klass
1261 if values.empty?
1262 send(name + "=", nil)
1263 else
1264 send(name + "=", Time == klass ? klass.local(*values) : klass.new(*values))
1265 end
1266 end
1267 end
1268
1269 def extract_callstack_for_multiparameter_attributes(pairs)
1270 attributes = { }
1271
1272 for pair in pairs
1273 multiparameter_name, value = pair
1274 attribute_name = multiparameter_name.split("(").first
1275 attributes[attribute_name] = [] unless attributes.include?(attribute_name)
1276
1277 unless value.empty?
1278 attributes[attribute_name] <<
b29c01e @dhh Added that has_and_belongs_to_many associations with additional attribut...
dhh authored
1279 [ find_parameter_position(multiparameter_name), type_cast_attribute_value(multiparameter_name, value) ]
db045db @dhh Initial
dhh authored
1280 end
1281 end
1282
1283 attributes.each { |name, values| attributes[name] = values.sort_by{ |v| v.first }.collect { |v| v.last } }
1284 end
1285
1286 def type_cast_attribute_value(multiparameter_name, value)
1287 multiparameter_name =~ /\([0-9]*([a-z])\)/ ? value.send("to_" + $1) : value
1288 end
1289
1290 def find_parameter_position(multiparameter_name)
1291 multiparameter_name.scan(/\(([0-9]*).*\)/).first.first
1292 end
1293
1294 # Returns a comma-separated pair list, like "key1 = val1, key2 = val2".
1295 def comma_pair_list(hash)
1296 hash.inject([]) { |list, pair| list << "#{pair.first} = #{pair.last}" }.join(", ")
1297 end
1298
1299 def quoted_column_names(attributes = attributes_with_quotes)
1300 attributes.keys.collect { |column_name| connection.quote_column_name(column_name) }
1301 end
1302
1303 def quote_columns(column_quoter, hash)
b29c01e @dhh Added that has_and_belongs_to_many associations with additional attribut...
dhh authored
1304 hash.inject({}) do |list, pair|
db045db @dhh Initial
dhh authored
1305 list[column_quoter.quote_column_name(pair.first)] = pair.last
1306 list
b29c01e @dhh Added that has_and_belongs_to_many associations with additional attribut...
dhh authored
1307 end
db045db @dhh Initial
dhh authored
1308 end
1309
1310 def quoted_comma_pair_list(column_quoter, hash)
1311 comma_pair_list(quote_columns(column_quoter, hash))
1312 end
1313
1314 def object_from_yaml(string)
b40d3c9 @dhh Replaced === checks with is_a? checks #502, #82 [Marcel Molina]
dhh authored
1315 return string unless string.is_a?(String)
db045db @dhh Initial
dhh authored
1316 if has_yaml_encoding_header?(string)
1317 begin
1318 YAML::load(string)
1319 rescue Object
1320 # Apparently wasn't YAML anyway
1321 string
1322 end
1323 else
1324 string
1325 end
1326 end
1327
1328 def has_yaml_encoding_header?(string)
1329 string[0..3] == "--- "
1330 end
1331 end
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindings ...
dhh authored
1332 end
Something went wrong with that request. Please try again.