6
我想创建一个自定义验证函数,只有当数据库中的当前字段不为空时,才会允许字段被保存为空/零。如何在验证函数中访问数据库值(旧值)?我可以使用self.name_of_field访问新值。Rails:在编辑验证过程中比较旧值和新值
这就是我现在所拥有的
validate :image_remote_url_change
def image_remote_url_change
if self.image_remote_url.blank? and self.image_remote_url_changed?
errors.add(:field, "can't be blank once set")
return false
end
end
现在,如果我尝试编辑现有的对象,它不会接受的空一个新的价值,但在创建新对象时,它会说“可以即使旧的价值从未设置过,一旦设置就没有空白“。
+1。来自Heroku的Schneems有一个[简要文章](http://schneems.com/post/28425724540/get-previously-saved-changes-in-rails)讨论previous_changes方法,它可能也会帮助你。 – stephenmurdoch
Doesn'这只是工作,但如果对象实际上改变?因为它被成功保存了。我只是在验证步骤上做这件事 –
@glumbo试一试,看看 – stephenmurdoch