如何设计销毁会话并从控制器退出?

fab*_*bbb 12 ruby ruby-on-rails devise ruby-on-rails-4

设计销毁会话并从控制器退出?

if something_is_not_kosher
  # 1. log this event, 2. send notice
  redirect_to destroy_user_session_path and return
end
Run Code Online (Sandbox Code Playgroud)

还尝试过:

if something_is_not_kosher
 # 1. log this event, 2. send notice
  redirect_to controller: 'devise/sessions', action: 'destroy', method: :delete and return
end
Run Code Online (Sandbox Code Playgroud)

错误是No route matches [GET] "/users/sign_out"但我明确设置方法::在示例2中删除.也许设计有一个方法?current_user.sign_out并试过sign_out(current_user)哪个也行不通?谢谢您的帮助.

耙路线:

        new_user_session GET    /users/sign_in(.:format)         devise/sessions#new
            user_session POST   /users/sign_in(.:format)         devise/sessions#create
    destroy_user_session DELETE /users/sign_out(.:format)        devise/sessions#destroy
           user_password POST   /users/password(.:format)        devise/passwords#create
       new_user_password GET    /users/password/new(.:format)    devise/passwords#new
      edit_user_password GET    /users/password/edit(.:format)   devise/passwords#edit
                         PATCH  /users/password(.:format)        devise/passwords#update
                         PUT    /users/password(.:format)        devise/passwords#update
cancel_user_registration GET    /users/cancel(.:format)          users/registrations#cancel
       user_registration POST   /users(.:format)                 users/registrations#create
   new_user_registration GET    /users/sign_up(.:format)         users/registrations#new
  edit_user_registration GET    /users/edit(.:format)            users/registrations#edit
                         PATCH  /users(.:format)                 users/registrations#update
                         PUT    /users(.:format)                 users/registrations#update
                         DELETE /users(.:format)                 users/registrations#destroy
Run Code Online (Sandbox Code Playgroud)

小智 14

你为什么不使用devise的内置sign_out_and_redirect(current_user)方法?


fab*_*bbb 8

所以我最终通过创建自定义注销路线解决了这个问题

  devise_scope :user do
    get '/signout', to: 'devise/sessions#destroy', as: :signout
  end
Run Code Online (Sandbox Code Playgroud)

在我的控制器中我有:

if something_is_not_kosher
  redirect_to signout_path and return
end
Run Code Online (Sandbox Code Playgroud)


ddd*_*919 6

destroy_user_session_path(@user)为用户注销路径,但必须使用DELETE方法.redirect_to方法会告诉broswer请求另一条路径,但broswer只能用GET方法请求.
因此,如果您想让用户注销,您必须使用DELETE方法或AJAX请求设置注销表单,以便用户注销但不能使用redirect_to功能.

如果您只想销毁用户会话,请使用即可sign_out @user.