2014-02-27 48 views
0

在模型只会验证我想要的东西,像下面如果其他在轨

validates :category, :presence => true if self.post = "this_is_post" 

是否有可能还是我必须使用钩子方法之前保存这个检查?

回答

3

这应该工作:

validates :category, :presence => true, :if => ->(a){ a.post == 'this_is_post' } 
+0

你能解释一下这里是什么。在模型中,我使用self.post来访问任何资源字段。 – asdfkjasdfjk

+0

@ user3128796如果你在这个':if'选项中传递了'Proc'对象,那么它将被传递给它的模型对象(在我的例子中用'a'引用)来评估。所以你可以直接调用它'post',就像你使用'regular'对象一样。 –

+0

@ user3128796还有什么不清楚的地方吗? –

0

这里,不止一个代码snippest在轨验证条件:

class Person < ActiveRecord::Base 
    validates :surname, presence: true, if: "name.nil?" 
end 

=============== =========

validates :category, 
     :presence => true, 
     :if => :valid? 

def valid? 
    self.post == "this_is_post" 
end 

================

class Person < ActiveRecord::Base 
    validates :category, presence: true, if: "self.post.eql?('this_is_post')" 
end 
+0

最后一个不工作,但我看起来像最后一个 – asdfkjasdfjk