在模型中,我想要类似下面的内容
validates :category, :presence => true if self.post = "this_is_post"
是否可以或者我必须在保存之前使用钩子方法进行此检查?
答案 0 :(得分:3)
这应该有效:
validates :category, :presence => true, :if => ->(a){ a.post == 'this_is_post' }
答案 1 :(得分:0)
此处,rails中有多个用于验证条件的代码段:
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