开发者

Ruby - Initializing a model

开发者 https://www.devze.com 2023-01-11 00:51 出处:网络
I don\'t know how to initialize information in a model before it is saved. For example.开发者_JS百科 I have a model called Car, and it has the attributes wheel_size, color, etc...

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

For example.开发者_JS百科 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


after_initialize

would be the best lifecycle hook


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消