Sam 山
Sam 山

Reputation: 42865

Ruby - Initializing a model

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

Upvotes: 1

Views: 1179

Answers (3)

Jed Schneider
Jed Schneider

Reputation: 14671

after_initialize

would be the best lifecycle hook

Upvotes: 3

Bob Aman
Bob Aman

Reputation: 33239

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

Upvotes: 1

Draiken
Draiken

Reputation: 3815

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

Upvotes: 0

Related Questions