在ActiveRecord中标记无效属性 [英] Flag invalid attribute in ActiveRecord
问题描述
我正在尝试实现以下功能:在ActiveRecord模型上,属性一旦设置就无法更改。为此,我编写了以下方法:
I am trying to implement functionality wherein an attribute, once set, cannot be changed on an ActiveRecord model. To this end, I have written the following methods:
def address
self[:address]
end
def address=(val)
if new_record?
self[:address] = val
else
errors.add(:address, "Cannot change address, once it is set")
return false # tried return nil here first, did not work
end
end
我在这里做错了吗?尝试更改地址后,我希望该对象无效,但是当我执行 obj.valid?
Am I doing something wrong here? I want the object to be invalid once I try to change an address, but I do not get any errors when I do obj.valid?
编辑:设置后该值不会更改,但通过obj.valid进行验证时我想获取无效的对象吗?
The value is not changed once it is set, but I would like to get invalid object when I do the validation via obj.valid?
推荐答案
当您执行 obj.valid?
时,它将清除所有错误,然后依次运行每个验证。要在验证时产生错误,您必须将该逻辑移至验证模块中。
When you do obj.valid?
, it clears all of your errors, and then runs each of the validations in turn. To have this produce an error on validation, you'll have to move that logic into a validation block.
下面是使用实例变量执行此操作的一种示例:
Here's an example of one way to do that with an instance variable:
def address=(val)
if new_record?
self[:address] = val
else
@addr_change = true
return false # tried return nil here first, did not work
end
end
validate do |user|
errors.add(:address, "Cannot change address, once it is set") if @addr_change
end
这篇关于在ActiveRecord中标记无效属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!