重定向到表单验证错误的路由别名

Kev*_*onk 5 ruby-on-rails cucumber

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

目前它是渲染/新的

我可以做一个redirect_to register_path然后我会丢失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."
Run Code Online (Sandbox Code Playgroud)

Tar*_*ast 1

另一种方法是设置两个“注册”路由。一个仅接受 GET 请求(并转到 :new 操作),另一个仅接受 POST 请求(并转到 create 操作,但呈现与 new 相同的模板)。

这可能看起来像:

map.get_register 'register', :controller => :registrations, 
                 :action => :new, :conditions => { :method => :get }
map.post_register 'register', :controller => :registrations, 
                 :action => :create, :conditions => { :method => :post }
Run Code Online (Sandbox Code Playgroud)

然后在你的控制器中:

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
Run Code Online (Sandbox Code Playgroud)

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