views:

54

answers:

3

I don't know how to initialize information in a model before it is saved.

For example. I have a model called Car, and it has the attributes wheel_size, color, etc... I want to initialize these attributes depending on other factors for each new car.

This is how I'm doing it right now.

Class Car < ActiveRecord::Base

    before_save :initial_information

    def initial_information
        self.color = value1
        self.wheel_size = value2
    end

end
+1  A: 

You want to do this initialization as early as possible; ideally immediately after the information you depend on is set. I'd recommend writing custom setter methods for the attributes these values depend on and initializing them there.

So, something like:

def value1=(new_value1)
  self["value1"] = new_value1
  self.color = new_value1
end

Alternatively, if these values can be directly calculated from the dependent variables, it's much better to simply use a normal method.

def color
  return self.value1
end
Bob Aman
When do these values get set?
Sam
The first approach I gave will set `color` every time you change the value of `value1` via the setter. So for example, after calling `model.value1 = "foo"`, the value of `model.color` would immediately be `"foo"`.
Bob Aman
+3  A: 

after_initialize

would be the best lifecycle hook

Jed Schneider
why is it the best lifecycle hook. What is a hook?
Sam
I guess since this was the selected answer, you figured out what a life cycle hook is?
Jed Schneider
A: 

by doing an after_initialize :mymethod your method mymethod will be called after the initialize (which is the constructor in ruby's objects) :]

Angelus