表单验证 - 如果出现错误,则需要进行此验证

时间:2012-08-08 16:21:43

标签: ruby-on-rails validation models

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

我目前的代码是:

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

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

2 个答案:

答案 0 :(得分: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是真还是假。使用unless表示仅在virtualfalse时执行此验证(或者是false的值)。

有关虚拟属性和验证的更多详细信息:Rails: Using form fields that are unassociated with a model in validations

答案 1 :(得分:0)

validates :location, presence: true, if: Proc.new { |p| p.virtual == false }