16

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?

4 Answers 4

39

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.

Sign up to request clarification or add additional context in comments.

2 Comments

this looks like EXACTLY what I wanted to do. I'll try it today when I get to work.
if you are using Devise and you don't wish to change the view, you could override RegistrationsController to set foobar[force_submit] in the params before sending it on to Devise::RegistrationsController. Don't forget to set 'attr_accessible :force_submit' in the model (Rails 3.x) or the force_submit won't be updated.
10

Try this:

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

It bypasses validations (all of them though).

5 Comments

My title was kind of misleading...I dont want to totally bypass all of my validations, just the 2 validates_uniqeness_of
Just stumbled upon this. You should use object.save(:validate => false) when using Rails 3.
Good point Jaap, I've submitted edit to add that to the answer.
Is there a version of this for create?
Thanks for this; this is exactly what I want to do: skip all validations. I didn't know it was this simple.
2

Not positive about this, but you could try to add an attr_accessor to your model to hold whether or not the form has been submited once before.

just add

attr_accessor :submitted

to your model and check for it in your validations.

Comments

1

You can just look at the submit button to determine whether you want to perform the validations.

def form_method
  case params[:submit]
    when "Submit" 
      'Do your validation here'
    when "Resubmit" 
      'Do not call validation routine'
  end
end

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.