Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails form validation conditional bypass

I have a rails model that validates uniqueness of 2 form values. If these 2 values aren't unique the validation errors are shows and the "submit" button is changed to "resubmit". I want to allow a user to click the "resubmit" button and bypass the model validation. I want to do something like this from the rails validation documentation:

validates_uniqueness_of :value, :unless => Proc.new { |user| user.signup_step <= 2 }

but I don't have a a value in my model that I can check for...just the params that have the "Resubmit" value.

Any ideas on how to do this?

like image 681
hacintosh Avatar asked Jan 08 '09 03:01

hacintosh


2 Answers

In my opinion this is the best way to do it:

class FooBar < ActiveRecord::Base
  validates_uniqueness_of :foo, :bar, :unless => :force_submit
  attr_accessor :force_submit
end

then in your view, make sure you name the submit tag like

<%= submit_tag 'Resubmit', :name => 'foo_bar[force_submit]' %>

this way, all the logic is in the model, controller code will stay the same.

like image 148
ucron Avatar answered Oct 15 '22 23:10

ucron


Try this:

Rails 2: Model.save(false)
Rails 3: Model.save(:validate => false)

It bypasses validations (all of them though).

like image 36
zenazn Avatar answered Oct 16 '22 00:10

zenazn