How to give a model a defaulted attribute?

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 D.’) 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.

-Rob

Rob B. http://agileconsultingllc.com
[email protected]

You use the after_initialize callback:

class Person < ActiveRecord::Base
def after_initialize
name = “John D.” 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.

Steve

On Jan 30, 2007, at 5:30 PM, Steve B. wrote:

is specified, I’d use the before_save callback instead - otherwise the
above should work fine.

Steve

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.)

-Rob

Rob B. http://agileconsultingllc.com
[email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs