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

时间:2016-06-05 18:00:58

标签: ruby-on-rails ruby validation attributes conditional

如果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

2 个答案:

答案 0 :(得分:3)

您需要传递:unless =>符号(表示要调用的方法),字符串(要执行的有效Ruby代码),要调用的Proc或包含多个这些的数组。

因此,您的验证线将是:

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

参见"条件验证"这里: http://guides.rubyonrails.org/active_record_validations.html#using-a-symbol-with-if-and-unless

答案 1 :(得分:1)

您可以通过将validate:false传递给save方法来执行此操作。喜欢这个

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,这是一个字符串,并且不会被视为布尔值,除非你在params中将它作为字符串。 :)