Module: ActiveRecord::Defaults::ClassMethods
- Defined in:
- lib/active_record/defaults.rb
Instance Method Summary collapse
-
#defaults(defaults, &block) ⇒ Object
(also: #default)
Define default values for attributes on new records.
Instance Method Details
#defaults(defaults, &block) ⇒ Object Also known as: default
Define default values for attributes on new records. Requires a hash of attribute => value
pairs, or a single attribute with an associated block. If the value is a block, it will be called to retrieve the default value. If the value is a symbol, a method by that name will be called on the object to retrieve the default value.
The following code demonstrates the different ways default values can be specified. Defaults are applied in the order they are defined.
class Person < ActiveRecord::Base defaults :name => ‘My name’, :city => lambda { ‘My city’ }
default :birthdate do |person| Date.today if person.wants_birthday_today? end
default :favourite_colour => :default_favourite_colour
def default_favourite_colour “Blue” end end
The defaults
and the default
methods behave the same way. Use whichever is appropriate.
The default values are only used if the key is not present in the given attributes.
p = Person.new p.name # “My name” p.city # “My city”
p = Person.new(:name => nil) p.name # nil p.city # “My city”
Default values for belongs_to associations
Default values can also be specified for an association. For instance:
class Student < ActiveRecord::Base belongs_to :school default :school => lambda { School.new } end
In this scenario, if a school_id was provided in the attributes hash, the default value for the association will be ignored:
s = Student.new s.school # => #<School: …>
s = Student.new(:school_id => nil) s.school # => nil
Similarly, if a default value is specified for the foreign key and an object for the association is provided, the default foreign key is ignored.
64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/active_record/defaults.rb', line 64 def defaults(defaults, &block) default_objects = case when defaults.is_a?(Hash) defaults.map { |attribute, value| Default.new(attribute, value) } when defaults.is_a?(Symbol) && block Default.new(defaults, block) else raise "pass either a hash of attribute/value pairs, or a single attribute with a block" end write_inheritable_array :attribute_defaults, [*default_objects] end |