Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

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