如何设计销毁会话并从控制器注销?
设计销毁会话并从控制器退出?
if something_is_not_kosher # 1. log this event, 2. send notice redirect_to destroy_user_session_path and return end
还尝试过:
if something_is_not_kosher # 1. log this event, 2. send notice redirect_to controller: 'devise/sessions', action: 'destroy', method: :delete and return end
错误是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
为什么不使用sign_out_and_redirect(current_user)
的内置sign_out_and_redirect(current_user)
方法?
所以我最终通过创建自定义注销路线解决了这个问题
devise_scope :user do get '/signout', to: 'devise/sessions#destroy', as: :signout end
在我的控制器中我有:
if something_is_not_kosher redirect_to signout_path and return end
destroy_user_session_path(@user)
是用户的注销路径,但必须使用DELETE
方法。 redirect_to
方法将告诉broswer请求另一个路径,但broswer只能请求GET
方法。
因此,如果您想让用户注销,您必须使用DELETE
方法或使用AJAX请求设置注销表单,以便用户注销但不能使用redirect_to
函数。
如果您只想销毁用户会话,请使用sign_out @user
。
以防万一有人不能直接使用它。
<% if user_signed_in? %> <%= link_to "Logout", destroy_user_session_path, :method => :delete %> <% else %> <%= link_to "Sign up now!", new_user_registration_path%> <% end %>