重定向到表单验证错误的路由别名 [英] redirect to a route alias on a form validation error

查看:143
本文介绍了重定向到表单验证错误的路由别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在一个路由别名,如/ register,我有一个表单错误,我渲染:新的,路径是可能的/注册仍然吗?

If I'm on a route alias such as /register and I have a form error and I render :new, is it possible for the path to be /register still?

此时它正在渲染/新

我可以做一个redirect_to register_path但是我会失去params?

I could do a redirect_to register_path but then I would lose the params?

这使得以下测试失败:

  Scenario: Try registering with a bad staff number
Given I am on the registration page
When I fill in "email" with "kevin@acme.com"
And I fill in "First Name" with "Kevin"
And I fill in "last name" with "Monk"
And I fill in "Employee Number" with "something barking123"
And I press "Register"
Then I should be on the registration page
And I should see "Your employee ID number looks incorrect."


推荐答案

另一种方法是设置两个路线。一个仅接受GET请求(并转到:新操作),另一个只接受POST请求(并转到创建操作,但呈现与新的相同的模板)。

An alternative would be to set up two "register" routes. One that accepts only GET requests (and goes to the :new action) and the other that accepts only POST requests (and goes to the create action, but renders the same template as for new).

这可能如下所示:

map.get_register 'register', :controller => :registrations, 
                 :action => :new, :conditions => { :method => :get }
map.post_register 'register', :controller => :registrations, 
                 :action => :create, :conditions => { :method => :post }

然后在您的控制器中:

def new
   @registration = Registration.new
   # renders the 'registrations/new' template
end
def create
   @registration = Registration.new(params[:registration])

   # render the 'registrations/new' template if we fail validation
   return render(:action => :new) unless @registration.save
   # otherwise renders the "create" template which is likely a thank-you
end

在这个问题上似乎有更多类似的事情:
在模型验证失败时使用自定义路线

There seems to be more in a similar vein on this question: Use custom route upon model validation failure

这篇关于重定向到表单验证错误的路由别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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