Rails:如何使用before_save更改基于另一个字段的字段值? [英] Rails: How to use before_save to change a field value based on another field?
问题描述
我正在尝试根据另一个布尔字段的值将布尔字段设置为false。我用ActiveRecord模型尝试了以下操作:
I'm trying to set a boolean field to false based on the value of another boolean field. I tried the following with an ActiveRecord model:
before_save :reconcile_xvent
def reconcile_xvent
self.xvent_hood = false if !self.xvent_plenum?
end
但这是行不通的。现在,我的许多单元测试都失败了:
But this doesn't work. Now, many of my unit tests fail with:
ActiveRecord::RecordNotSaved: ActiveRecord::RecordNotSaved
如果xvent_plenum为假,如何将xvent_hood设置为假?
How can I set xvent_hood to be false if xvent_plenum is false?
更新
有效的方法(其中一些来自下面的评论/答案):
Here's what works (some of which comes from the comments/answers below):
before_validation :reconcile_xvent
def reconcile_xvent
if self.xvent_hood?
self.xvent_hood = false unless xvent_plenum?
end
end
我不知道要不让它起作用如果self.xvent_hood?部分...。
I couldn't figure out to make it work without the "if self.xvent_hood?" part....
推荐答案
before_save
仅 在验证通过后调用。您需要做的是将 reconcile_xvent
移至 before_validation
而不是 before_save
before_save
is only called after validation has passed. What you need to do is move reconcile_xvent
up to before_validation
rather than before_save
如果将该方法保留在 before_save
中,将会发生的事情是它认为 xvent_hood
为空,如果您具有用于验证 xvent_hood
的无效性的验证,它将在 before_save <之前失败。 / code>被调用。这可能解释了为什么您出现
RecordNotSaved
错误。
If you keep that method in before_save
what will happen is that it thinks that xvent_hood
is null, if you have a validation that checks for nullity of xvent_hood
it will fail before the before_save
gets called. Which probably explains why you got RecordNotSaved
error.
要记住的另一件事是,如果您有布尔值属性,您也不能使用 validate_presence_of
。参见 http://alexanderwong.me/post/16084280769/rails-validate布尔型和数组类猴子的存在
Another thing to keep in mind is that if you have a boolean property, you also can't use validate_presence_of
. See http://alexanderwong.me/post/16084280769/rails-validate-presence-of-boolean-and-arrays-mongoid
这篇关于Rails:如何使用before_save更改基于另一个字段的字段值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!