如何绕过基于对象属性的模型验证?

How to Bypass Model Validation Based Upon Object Attribute?

如果 someday 布尔值等于 true 那么如何跳过验证?

challenge.rb

validates :name, :categorization, :category, presence: true, :unless => (:someday == true)

challenges_controller

def create
  if params[:challenge][:someday] == "1" # I had to use "1" instead of "true" for this conditional to work
    # saves challenges
  else
    # brings to create.html.erb and then saves
  end
end

您可以通过将 validate: false 传递给保存方法来实现。像这样

def create
  if params[:challenge][:someday] == "1" # I had to use "1" instead of "true" for this conditional to work
    @item = item.new(item_params)
    @item.save(validate: false)
  else
    # brings to create.html.erb
  end
end

还有一点需要注意,如果您在引号内使用 1,那是一个字符串,不会被视为布尔值,除非您在参数中将其作为字符串获取。 :)

您需要传递 :unless => 一个符号(表示要调用的方法)、一个字符串(要执行的有效 Ruby 代码)、要调用的 Proc 或包含多个其中之一。

因此,您的验证行将是:

validates :name, :categorization, :category, presence: true, unless: { |challenge| challenge.someday }

请在此处查看 "Conditional Validation": http://guides.rubyonrails.org/active_record_validations.html#using-a-symbol-with-if-and-unless