gpt4 book ai didi

ruby-on-rails-3 - 在ajax中设计处理注销重定向

转载 作者:行者123 更新时间:2023-12-01 06:51:50 25 4
gpt4 key购买 nike

我有一个带有 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?

请求由正确的 Controller 方法处理。然后我就有了

  def after_sign_out_path_for(resource)
root_path
end

这是日志

[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/

Hoverer,重定向由 Rails Controller 处理,实际上重定向使用了相同的动词“DELETE”。

[2012/12/11 15:44:13] (INFO) 76430 Started DELETE "/" 
[2012/12/11 15:44:13] (INFO) 76430 Processing by HomeController#index as */*

是否可以在客户端处理重定向并防止 Rails Controller 捕获它?我预计该设备将由于 ajax 调用而将 301/302 返回给客户端。

最佳答案

实际上我也遇到了同样的问题。可以覆盖 Devise::SessionsController,这就是我解决它的方法。

Devise::SessionsController 中,有一个 method #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

这有一个明显的问题,因为重写这样的私有(private)方法并不好(使用它的实现可能会在我们没有意识到的情况下发生变化),但我找不到任何其他方法来很好地做到这一点。在这种情况下,如果 Devise 让您能够渲染而不是重定向,那就太好了。

关于ruby-on-rails-3 - 在ajax中设计处理注销重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13822431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com