And*_*ich 1 jquery devise ruby-on-rails-3
我有一个带有 Rails/Devise 服务器的 Backbone.js 客户端。
我想通过重定向实现注销过程。
这是我的客户端代码
$.ajax
url: "/sign_out"
xhrFields:
'X-CSRF-Token': $('meta[name=csrf-token]').attr('content')
type: "DELETE"
complete: xCompleteFunction = (XMLHttpRequest, textStatus) ->
#handle here?
Run Code Online (Sandbox Code Playgroud)
请求由适当的控制器方法处理。然后我有
def after_sign_out_path_for(resource)
root_path
end
Run Code Online (Sandbox Code Playgroud)
这是日志
[2012/12/11 15:44:07] (INFO) 76430 Started DELETE "/sign_out"
[2012/12/11 15:44:07] (INFO) 76430 Processing by Devise::SessionsController#destroy as */*
....
[2012/12/11 15:44:07] (INFO) 76430 Redirected to http://localhost:3000/
Run Code Online (Sandbox Code Playgroud)
Hoverer,重定向由 Rails 控制器处理,实际上重定向使用了相同的动词“DELETE”。
[2012/12/11 15:44:13] (INFO) 76430 Started DELETE "/"
[2012/12/11 15:44:13] (INFO) 76430 Processing by HomeController#index as */*
Run Code Online (Sandbox Code Playgroud)
是否可以在客户端处理重定向,并防止 Rails 控制器捕获它?我期待设计将 301/302 作为 ajax 调用的结果返回给客户端。
我实际上也遇到了同样的问题。可以覆盖Devise::SessionsController,这就是我解决它的方式。
在 中Devise::SessionsController,有一个方法 #respond_to_on_destroy可以实际进行重定向。通过覆盖这个,它只是 200 的。
class SessionsController < Devise::SessionsController
private
# We sign out using Ajax calls so we override this method to render plain
# text instead of redirecting unnecessarily
def respond_to_on_destroy
respond_to do |format|
format.all { head :no_content }
format.any(*navigational_formats) { render plain: "Signed out" }
end
end
end
Run Code Online (Sandbox Code Playgroud)
这有一个明显的问题,因为覆盖这样的私有方法并不是很好(使用它的实现可能会在我们没有意识到的情况下发生变化),但我找不到任何其他方法可以很好地做到这一点。如果在这种情况下设计让您渲染而不是重定向,那就太好了。