标记 ActiveRecord 中的无效属性

发布于 2024-10-19 19:23:30 字数 450 浏览 6 评论 0原文

我正在尝试实现以下功能:属性一旦设置,就无法在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

佼人 2024-10-26 19:23:30

当您执行 obj.valid? 时,它会清除所有错误,然后依次运行每个验证。要使其在验证时产生错误,您必须将该逻辑移至验证块中。

下面是使用实例变量执行此操作的一种方法的示例:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文