Flag invalid attribute in ActiveRecord

三世轮回 提交于 2019-12-05 20:04:31

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!