[英]How do I set attributes in an ActiveRecord Object only if it is nil?
Sorry, I think I am a bit stupid today 对不起,我今天有点傻
class Mutant < ActiveRecord::Base
attr_accessible :style
before_create :setup_values
private
def setup_values
style = "hardcore" unless style
end
end
I like to call this stuff in the console like 我喜欢在控制台中称呼这些东西
Mutant.create(:style => "rampage") # expected is Mutant.first.style == "rampage"
Mutant.create # expected is Mutant.last.style == "hardcore but this doesn't work
style = "hardcore" unless style
will instantiate a new variable named 'style' rather than setting the existing property. style = "hardcore" unless style
将实例化名为'style'的新变量,而不是设置现有属性。 Change it to reference self like so: self.style = "hardcore" unless style
像这样将其更改为引用self : self.style = "hardcore" unless style
self.style ||= "hardcore"
which is a shortcut for what you've currently written. 最后,如下所示将分配写到self.style ||= "hardcore"
,这是您当前编写的快捷方式。 I'd probably write it like this: 我可能会这样写:
class Mutant < ActiveRecord::Base
attr_accessible :style
after_initialize :setup_values
private
def setup_values
self.style ||= "hardcore"
end
end
just found it in the api 刚刚在api中找到了它
def setup_values
write_attribute :style, "hardcore" if style.blank?
end
tadaa and it works :) 塔达阿,它的工作原理:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.