AnthonyGalli.com AnthonyGalli.com - 6 months ago 21
Ruby Question

How to Bypass Model Validation Based Upon Object Attribute?

If

someday
boolean is equal to
true
than how to skip validations?

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

Answer

You can do it by passing a validate: false to your save method. Like this

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

One more thing to note, it you're using 1 inside quotes, that's a string, and won't be considered as a boolean, unless you get it as a string in your params. :)