在模型中设置属性
所以我有一个应用程序,它只需要一些 RSS 提要并将它们存储在表中。它检查每个条目中的一些条件,然后根据条件设置属性。
if self.value1 > self.value2 then
:status => 'foo'
else
:status => 'bar'
end
我对 Ruby/Rails 还是有点菜鸟,设置状态会导致异常,但我不知道为什么。
任何帮助都会很棒。
So I've got an application which simply takes a number of RSS feeds and stores them in a table. It checks a couple of things in each entry for conditions and then sets an attribute based on the condition.
if self.value1 > self.value2 then
:status => 'foo'
else
:status => 'bar'
end
I'm still a bit of a noob with Ruby/Rails and setting the status is causing an exception but I don't know why.
Any help would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您说“设置属性”时,我假设您的意思是这是表上的另一列。如果是这样,这应该可行:
在实例化对象或更新多个属性时(
self.update_attributes :动物=>“小猫”,:声音=>“咆哮!”
)。这是 Hash 使用的表示法。您也可以只使用
status = "foo"
,但这会设置属性而不保存,因此您还必须调用self.save
。update_attribute
在一个简洁的包中完成这两项任务。When you say "sets an attribute", I assume that you mean this is another column on the table. If so, this should work:
The "rocket" notation (
:this => "that"
) is used when instantiating an object, or when updating more than one attribute (self.update_attributes :animal => "kitten", :sound => "Roar!"
). It's the notation that a Hash uses.You could also just use
status = "foo"
, but that will set the attribute without saving, so you'd also have to callself.save
.update_attribute
does both in one neat package.在 Rails 4 中,我使用了以下方法:
并在模型中添加了 before_update 过滤器。
在此方法中,我们不需要调用 save 或 update_attributes,这将在单个查询中完成。
In Rails 4 I have done with the following method:
and added before_update filter in model.
In this method we don't need to call the save or update_attributes this will be done in a single query.