Rails 表单验证条件绕过 [英] Rails form validation conditional bypass

查看:27
本文介绍了Rails 表单验证条件绕过的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Rails 模型,可以验证 2 个表单值的唯一性.如果这 2 个值不是唯一的,则会显示验证错误并且提交"按钮更改为重新提交".我想允许用户单击重新提交"按钮并绕过模型验证.我想从 Rails 验证文档中做这样的事情:

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.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?

推荐答案

在我看来这是最好的方法:

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.

这篇关于Rails 表单验证条件绕过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆