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
1

3 Answers 3

3

after_initialize

would be the best lifecycle hook

Sign up to request clarification or add additional context in comments.

2 Comments

why is it the best lifecycle hook. What is a hook?
I guess since this was the selected answer, you figured out what a life cycle hook is?
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

2 Comments

When do these values get set?
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".
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.