Rails 3.2 防止使用错误保存对象 [英] Rails 3.2 Prevent Object from being Saved using Errors

查看:52
本文介绍了Rails 3.2 防止使用错误保存对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ActiveRecord 对象,我想防止它被保存,而无需对模型进行永久验证.您过去可以使用 errors.add 执行类似的操作,但现在看起来不再有效.

I have an ActiveRecord object and I would like to prevent it from being saved, without having permanent validations on the model. You used to be able to do something like this using errors.add but it doesn't look like it works anymore.

user = User.last
user.errors.add :name, "name doesn't rhyme with orange"
user.valid? # => true
user.save   # => true

user = User.last
user.errors.add :base, "my unique error"
user.valid? # => true
user.save   # => true

如何在不修改模型的情况下防止用户对象保存在 Rails 3.2 中?

How can I prevent the user object from getting saved in Rails 3.2 without modifying it's model?

推荐答案

您可以设置 errors,但要在验证方法中进行,例如:

You can set errors, but do it within a validate method, e.g.:

validate :must_rhyme_with_orange

def must_rhyme_with_orange
  unless rhymes_with_orange?
    errors.add(:name, "doesn't rhyme with orange")
  end
end

如果你想有条件地运行验证,一个技巧是使用 attr_accessor 和一个保护条件:

If you want to conditionally run the validation, one trick is to use attr_accessor and a guard condition:

attr_accessor :needs_rhyming

validate :must_rhyme_with_orange, :if => Proc.new {|o| o.needs_rhyming}

> u = User.last
> u.needs_rhyming = true
> u.valid? # false

这篇关于Rails 3.2 防止使用错误保存对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆