views:

197

answers:

2

I've just been reading this question which is about giving an ActiveRecord model's date field a default value. The accepted answer shows how to set the default value from within the controller. To my mind, this sort of business logic really belongs in the model itself.

Then I got to thinking how if this were Java I'd probably set the initial field value when declaring the instance variable or within the constructor. Since database-backed fields don't have to be explicitly declared within ActiveRecord models, is this something that you could use the model's initialize method for? I'm curious because I've not really seen much use of constructors for ActiveRecord models within the Rails code that I've looked at. Do they have a role to play and if so, what is it?

A: 

According to this blog, active record doesn't always use new, so initialize might not be called on your object.

JRL
+5  A: 

I do this quite often actually for default values. It works well and still lets the user change it. Remember, the initialize method is called when you say MyObject.new. However, you may want to read this blog entry (albeit a bit outdated) about using initialize.

You should use after_initialize instead of initialize. The initialize method is required by ActiveRecord::Base to prepare many of the convenience methods. If an after_initialize method is defined in your model it gets called as a callback to new, create, find and any other methods that generate instances of your model.

Ideally you'd want to define it like this:

def after_initialize
  @attribute ||= default_value
end

Also note, you cannot use this callback like the others, you must define a method named after_initialize (like above) for it to work. You can't do the following:

after_initialize :run_some_other_method
Topher Fangio
I use a similar technique to cache internal attributes based on fields instead of doing the same calculations over and over again.
EmFi