Rails条件验证无法正常工作

时间:2016-06-05 20:07:14

标签: ruby-on-rails ruby-on-rails-4

我正在尝试设置条件验证,并且我传递给它的方法是否返回truefalse对象将保存。

test返回false时,我不希望该对象保存

class Foo < ActiveRecord::Base
  belongs_to :order
  belongs_to :user

  validates :order, presence: true
  validates :user, presence: true, if: :test

  private

  def test
    false
  end
end

控制器:

def create
  foo = Foo.new(foo_params)

  if foo.save
    render json: delivery, status: 201
  else
    render json: { errors: foo }, status: 422
  end
end

1 个答案:

答案 0 :(得分:2)

对于您的情况,如果:test返回false,则会跳过user验证。但是,如果您希望强制验证始终失败,请替换验证器并将值传递给它:

应用/验证/ custom_presence_validator.rb

class CustomPresenceValidator < AM::EachValidator
   def validate_each record, attribute, value
      if options[:with].try(:[], :fail)
         record.errors[ attribute ] << 'forced fail'
      elsif value.blank?
         record.errors[ attribute ] << 'can\'t be blank'
      end
   end
end

并使用它:

validates :user, custom_presence: { fail: true }

或者根据您的意愿,您也可以:before_save