Skip to content

HTTPS clone URL

Subversion checkout URL

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