对不起,我觉得我今天有点傻了
class Mutant < ActiveRecord::Base
attr_accessible :style
before_create :setup_values
private
def setup_values
style = "hardcore" unless style
end
end
我喜欢在控制台中调用这些东西,比如
Mutant.create(:style => "rampage") # expected is Mutant.first.style == "rampage"
Mutant.create # expected is Mutant.last.style == "hardcore but this doesn't work
答案 0 :(得分:1)
style = "hardcore" unless style
将实例化一个名为“style”的新变量,而不是设置现有属性。将其更改为引用 self ,如下所示:self.style = "hardcore" unless style
self.style ||= "hardcore"
这是您当前所写内容的快捷方式。我可能会这样写:
class Mutant < ActiveRecord::Base
attr_accessible :style
after_initialize :setup_values
private
def setup_values
self.style ||= "hardcore"
end
end
答案 1 :(得分:0)
刚刚在api中找到它
def setup_values
write_attribute :style, "hardcore" if style.blank?
end