简体   繁体   English

Rails形成验证条件绕过

[英]Rails form validation conditional bypass

I have a rails model that validates uniqueness of 2 form values. 我有一个rails模型,可以验证2个表单值的唯一性。 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: 我想从rails验证文档中做这样的事情:

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

but I don't have aa value in my model that I can check for...just the params that have the "Resubmit" value. 但是我的模型中没有一个我可以检查的值......只是具有“重新提交”值的参数。

Any ideas on how to do this? 关于如何做到这一点的任何想法?

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. 这样,所有逻辑都在模型中,控制器代码将保持不变。

Try this: 试试这个:

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

It bypasses validations (all of them though). 它绕过了验证(尽管它们都是)。

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. 对此并不积极,但你可以尝试在你的模型中添加一个attr_accessor来保存表单是否已经被提交过一次。

just add 加上

attr_accessor :submitted

to your model and check for it in your validations. 到您的模型并在验证中检查它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM