标记 ActiveRecord 中的无效属性
我正在尝试实现以下功能:属性一旦设置,就无法在 ActiveRecord 模型上更改。为此,我编写了以下方法:
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?
时,我没有收到任何错误
编辑:该值一旦设置就不会更改,但我当我通过 obj.valid 进行验证时想获得无效对象吗?
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
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?
EDIT: 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您执行 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: