Rails form validation conditional bypass

后端 未结 4 590
眼角桃花
眼角桃花 2020-12-08 11:34

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 \"

相关标签:
4条回答
  • 2020-12-08 12:12

    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.

    0 讨论(0)
  • 2020-12-08 12:12

    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
    
    0 讨论(0)
  • 2020-12-08 12:13

    Try this:

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

    It bypasses validations (all of them though).

    0 讨论(0)
  • 2020-12-08 12:28

    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.

    0 讨论(0)
提交回复
热议问题