Rails 条件验证 [英] Rails Conditional Validation
本文介绍了Rails 条件验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我这里有两个模型:
So I have two models here:
class Screen < ActiveRecord::Base
belongs_to :user
validates :screen_size, :numericality =>{:less_than_or_equal_to =>100,:greater_than_or_equal_to => 0},:if => "user.access==1"
class User < ActiveRecord::Base
has_many :screens
attr_accessible :access
但是这段代码不起作用,因为无论user.access是什么值,它仍然会执行验证.我在这里做错了什么?
But this code doesn't work, cause no matter what value the user.access is, it will still execute the validation. What am I doing wrong here?
谢谢
推荐答案
更改:
:if => "user.access==1"
与:
:if => lambda { |screen| screen.user.try(:access) ==1 }
因为:
您需要传递一个函数来即时评估条件
you need to pass a function to evaluate condition on the fly
如果你的屏幕没有任何用户,仅仅一个screen.user.access
就会抛出异常
if your screen doesn't have any user, a mere screen.user.access
would throw an exception
这篇关于Rails 条件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文