I know that something similar could be done at the database schema level, but I wonder if this is the right way to give an ActiveRecord model a defaulted attribute:
class Person < ActiveRecord::Base
def initialize(options={})
super
write_attribute(:name, ‘John Doe’) if read_attribute(:name).blank?
end
end
It seems to work, meaning:
def test_has_name_by_default
new_person = Person.new
assert_not_nil new_person.name
end
But I’m a bit suspicious that there is a better/safer way that I don’t see.
class Person < ActiveRecord::Base
def after_initialize
name = "John Doe" if name.blank?
end
end
If you just need a default value to be saved to the database if none
is specified, I'd use the before_save callback instead - otherwise the
above should work fine.
Thanks. After seeing the special treatment described for after_initialize (and after_find) in the API docs, I'm thinking that this isn't the best idea and that I may just use a before_create in the model and not worry about the field being empty (uninitialized) in the new view. (Since I don't want this to go into view or controller code.)