1

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
thenengah
  • 42,557
  • 33
  • 113
  • 157
  • 1
    Check this post on SO: http://stackoverflow.com/questions/328525/what-is-the-best-way-to-set-default-values-in-activerecord – Daniel O'Hara Aug 06 '10 at 18:22

3 Answers3

3

after_initialize

would be the best lifecycle hook

Jed Schneider
  • 14,085
  • 4
  • 35
  • 46
1

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
  • 32,839
  • 9
  • 71
  • 95
  • When do these values get set? – thenengah Aug 06 '10 at 18:48
  • 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 Aug 06 '10 at 21:44
0

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

Draiken
  • 3,805
  • 2
  • 30
  • 48