2016-09-03 102 views
0

在我的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 

但它不工作。我怎样才能循环对我的对象p​​ropertie“指针”?

回答

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? 
} 
+0

非常感谢你,它完美的作品! – RousseauAlexandre

+0

不错,一个小窍门是你可以跳过将方法名称转换为符号,'.send'对字符串完美地工作。 – max

+0

是真实的,但据我所知,使用符号效率更高一些。问题是,如果你在应用程序的不同位置使用了符号':foobar',它们具有相同的'object_id',这对于字符串来说不是这样(双重内存分配) – djaszczurowski