假设我正在使用一个表单和一个标准的 Rails restful Controller 创建一个新的 Foo,它看起来像这样:
class FoosController < ApplicationController
...
def index
@foos = Foo.all
end
def new
@foo = Foo.new
end
def create
@foo = Foo.create(params[:foo])
if @foo.save
redirect_to foos_path, :notice => 'Created a foo.'
else
render 'new'
end
end
...
end
所以,如果我使用标准的 restful Controller (如上),那么当我创建 Foo 时,我在
example.com/foos/new
,如果我提交表单并正确保存,我在 example.com/foos
显示索引操作。但是,如果未正确填写表单,则会再次呈现表单并显示错误消息。这都是普通的 Vanilla 。但是,如果显示错误,将呈现表单页面,但 URL 将是
example.com/foos
,因为 CREATE 操作发布到该 url。然而,人们会期望在 example.com/foos
找到 Foos#index ,而不是他们现在刚刚提交并添加了错误消息的表单。这似乎是 Rails 的标准行为,但对我来说没有多大意义。显然,我可以重定向回 new 而不是从 create 操作中渲染 new,但问题是错误消息等会随着内存中部分完整的 Foos 丢失。
有没有针对这个问题的干净解决方案,一种将人们送回
example.com/foos/new
的方法?当他们提交的新 Foo 表单中出现错误时?谢谢!
最佳答案
要回答您对另一个答案的评论:
I'm wondering if there's a way, without rewriting the controller at all, to tell rails that you want the URL to match the rendered template, rather than the controller action that called it.
我不这么认为; URL 直接绑定(bind)到路由,路由绑定(bind)到 Controller 和操作对——渲染层根本不接触它。
回答 你原来的问题 , 这里的信息来自 another similar question我回答了。
如您所见,默认情况下,当您指定
resources :things
,创建新事物的 POST 路径为 /things
.这是 rake routes
的输出: things GET /things(.:format) {:action=>"index", :controller=>"things"}
POST /things(.:format) {:action=>"create", :controller=>"things"}
new_thing GET /things/new(.:format) {:action=>"new", :controller=>"things"}
edit_thing GET /things/:id/edit(.:format) {:action=>"edit", :controller=>"things"}
thing GET /things/:id(.:format) {:action=>"show", :controller=>"things"}
PUT /things/:id(.:format) {:action=>"update", :controller=>"things"}
DELETE /things/:id(.:format) {:action=>"destroy", :controller=>"things"}
听起来你想要更像这样的东西:
create_things POST /things/new(.:format) {:action=>"create", :controller=>"things"}
things GET /things(.:format) {:action=>"index", :controller=>"things"}
new_thing GET /things/new(.:format) {:action=>"new", :controller=>"things"}
edit_thing GET /things/:id/edit(.:format) {:action=>"edit", :controller=>"things"}
thing GET /things/:id(.:format) {:action=>"show", :controller=>"things"}
PUT /things/:id(.:format) {:action=>"update", :controller=>"things"}
DELETE /things/:id(.:format) {:action=>"destroy", :controller=>"things"}
虽然不推荐,但您可以通过以下路线获得此结果:
resources :things, :except => [ :create ] do
post "create" => "things#create", :as => :create, :path => 'new', :on => :collection
end
您还需要修改表单以使它们 POST 到正确的路径。
关于ruby-on-rails - rails : URL after validation fails when creating new records via form,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5347917/