类对象上的指针

时间:2016-09-03 10:35:06

标签: ruby-on-rails ruby

在我的Ruby模型中,我想在Recipe的某些属性上应用默认值。所以我添加了一个before_save回调来应用它:这是我的食谱模型:

class Recipe < ActiveRecord::Base
    before_save :set_default_time

    # other stuff

    private

    # set default time on t_baking, t_cooling, t_cooking, t_rest if not already set
    def set_default_time
        zero_time = Time.new 2000, 1 ,1,0,0,0

        self.t_baking   = zero_time unless self.t_baking.present?
        self.t_cooling  = zero_time unless self.t_cooling.present?
        self.t_cooking  = zero_time unless self.t_cooking.present?
        self.t_rest     = zero_time unless self.t_rest.present?
    end

end

这是相当不错的工作,但我想将它分解为:

class Recipe < ActiveRecord::Base
    before_save :set_default_time

    # other stuff

    private

    # set default time on t_baking, t_cooling, t_cooking, t_rest if not already set
    def set_default_time
        zero_time = Time.new 2000, 1 ,1,0,0,0

        [self.t_baking, self.t_cooling, self.t_cooking, self.t_rest].each{ |t_time|
            t_time = zero_time unless t_time.present?
        }

    end

end

但它不起作用。如何在我的对象属性上循环“指针”?

1 个答案:

答案 0 :(得分:1)

它不会起作用,因为你严格指代价值,因此你的覆盖不会按预期工作。你可以试试这个:

[:t_baking, :t_cooling, :t_cooking, :t_rest].each { |t_time|
  self.send("#{t_time}=".to_sym, zero_time) unless self.send(t_time).present?
}