0

在我对模型的表单验证中,我想说如果名为的列的参数:virtual为 false,则该:location字段应验证:presence => true.

我目前的代码是:

validates :location, if :virtual => false, :presence => true

但这给了我一个语法错误。格式化这个的正确方法是什么?

4

2 回答 2

1

就像是:

attr_accessor :virtual  # sets up a "virtual attribute" called "virtual" to which you can read/write a value
                        # this step isn't necessary if you already have an attribute on the model called "virtual"

validates :location, :presence => true, :unless => :virtual?

的使用virtual?应该检查属性virtual是真还是假。使用意味着仅在is (或被考虑的值)unless时才执行此验证。virtualfalsefalse

有关虚拟属性和验证的更多详细信息:Rails:在验证中使用与模型无关的表单字段

于 2012-08-08T16:34:32.637 回答
0
validates :location, presence: true, if: Proc.new { |p| p.virtual == false }
于 2012-08-08T16:49:39.577 回答