@@ -310,36 +310,40 @@ def attribute_present?(attr_name)
310
310
!value . nil? && !( value . respond_to? ( :empty? ) && value . empty? )
311
311
end
312
312
313
- # Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
314
- # "2004-12-12" in a date column is cast to a date object, like <tt>Date.new(2004, 12, 12)</tt>). It raises
315
- # ActiveModel::MissingAttributeError if the identified attribute is missing.
316
- #
317
- # Note: +:id+ is always present.
313
+ # Returns the value of the attribute identified by +attr_name+ after it has
314
+ # been type cast. (For information about specific type casting behavior, see
315
+ # the types under ActiveModel::Type.)
318
316
#
319
317
# class Person < ActiveRecord::Base
320
318
# belongs_to :organization
321
319
# end
322
320
#
323
- # person = Person.new(name: 'Francesco', age: '22')
324
- # person[:name] # => "Francesco"
325
- # person[:age] # => 22
321
+ # person = Person.new(name: "Francesco", date_of_birth: "2004-12-12")
322
+ # person[:name] # => "Francesco"
323
+ # person[:date_of_birth] # => Date.new(2004, 12, 12)
324
+ # person[:organization_id] # => nil
325
+ #
326
+ # Raises ActiveModel::MissingAttributeError if the attribute is missing.
327
+ # Note, however, that the +id+ attribute will never be considered missing.
326
328
#
327
- # person = Person.select('id').first
328
- # person[:name] # => ActiveModel::MissingAttributeError: missing attribute: name
329
+ # person = Person.select(:name).first
330
+ # person[:name] # => "Francesco"
331
+ # person[:date_of_birth] # => ActiveModel::MissingAttributeError: missing attribute: date_of_birth
329
332
# person[:organization_id] # => ActiveModel::MissingAttributeError: missing attribute: organization_id
333
+ # person[:id] # => nil
330
334
def []( attr_name )
331
335
read_attribute ( attr_name ) { |n | missing_attribute ( n , caller ) }
332
336
end
333
337
334
- # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
338
+ # Updates the attribute identified by +attr_name+ using the specified
339
+ # +value+. The attribute value will be type cast upon being read.
335
340
#
336
341
# class Person < ActiveRecord::Base
337
342
# end
338
343
#
339
344
# person = Person.new
340
- # person[:age] = '22'
341
- # person[:age] # => 22
342
- # person[:age].class # => Integer
345
+ # person[:date_of_birth] = "2004-12-12"
346
+ # person[:date_of_birth] # => Date.new(2004, 12, 12)
343
347
def []=( attr_name , value )
344
348
write_attribute ( attr_name , value )
345
349
end
0 commit comments