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
但它不工作。我怎样才能循环对我的对象propertie“指针”?
非常感谢你,它完美的作品! – RousseauAlexandre
不错,一个小窍门是你可以跳过将方法名称转换为符号,'.send'对字符串完美地工作。 – max
是真实的,但据我所知,使用符号效率更高一些。问题是,如果你在应用程序的不同位置使用了符号':foobar',它们具有相同的'object_id',这对于字符串来说不是这样(双重内存分配) – djaszczurowski