在我的模型表单验证中,我试图说如果名为:virtual
的列的参数为false,则:location
字段应验证:presence => true
。
我目前的代码是:
validates :location, if :virtual => false, :presence => true
但那给了我一个语法错误。格式化的正确方法是什么?
答案 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
表示仅在virtual
为false
时执行此验证(或者是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 }