在我的 Controller 中,我有这个:
class TestController < ApplicationController
respond_to :html, :json
# code...
def create
@test = current_user.tests.create(params[:test])
respond_with @test, location: tests_url
end
# code...
end
这很酷,当我创建
test
时,它重定向到 test#index
(正如预期的那样),但是,如果我按 F5
,浏览器要求我重新提交表单。如果我删除
location
声明来自 respond_with
它工作得很好,但没有转到我想要的 URL。我怎么能解决这个问题?
提前致谢。
编辑
我改变我的方法
@test = current_user.tests.new(params[:transaction])
respond_with(@test) do |format|
format.html { redirect_to "/tests/" } if @test.save
end
它有效......但是,我不得不使用字符串而不是
tests_url
有点奇怪.编辑 2
看到这个 complete example code和
Bug report .
编辑 3
我无法用 Ruby 1.9.3-p327 重现它,只能在 -p385 中重现。
最佳答案
您可以使用 redirect_to
方法,像这样:
def create
@test = current_user.tests.create(params[:test])
respond_with @test do |format|
format.html { redirect_to tests_path }
end
end
然后,如果客户端要求 json 响应,默认
to_json
行为将被触发,但如果所需的响应格式是 html,则将发送重定向。
关于ruby-on-rails - Rails Responder 在创建时重定向到索引导致形成奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14836001/