Ruby-on-rails 如何清空/销毁 Rails 中的会话?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2405635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:22:44  来源:igfitidea点击:

How to empty/destroy a session in rails?

ruby-on-railssessionsession-variablessession-timeout

提问by tybro0103

I can't seem to find it anywhere... How do I delete/destroy/reset/empty/clear a user's session in Rails? Not just one value but the whole thing..

我似乎在任何地方都找不到它...如何在 Rails 中删除/销毁/重置/清空/清除用户的会话?不只是一个价值,而是整个事情..

回答by Gdeglin

To clear the whole thing use the reset_session method in a controller.

要清除整个事情,请使用控制器中的 reset_session 方法。

reset_session

Here's the documentation on this method: http://api.rubyonrails.org/classes/ActionController/Base.html#M000668

这是有关此方法的文档:http: //api.rubyonrails.org/classes/ActionController/Base.html#M000668

Resets the session by clearing out all the objects stored within and initializing a new session object.

通过清除存储在其中的所有对象并初始化新会话对象来重置会话。

Good luck!

祝你好运!

回答by Lavixu

session in rails is a hash object. Hence any function available for clearing hash will work with sessions.

rails 中的 session 是一个哈希对象。因此,任何可用于清除散列的函数都适用于会话。

session.clear

or if specific keys have to be destroyed:

或者如果必须销毁特定的密钥:

session.delete(key)

Tested in rails 3.2

在 Rails 3.2 中测试

added

添加

People have mentioned by session={}is a bad idea. Regarding session.clear, Lobati comments- It looks like you're probably better off using reset_session [than session.clear], as it does some other cleaning up beyond what session.clear does. Internally, reset_session calls session.destroy, which itself calls clear as well some other stuff.

人们提到过session={}是一个坏主意。关于session.clear, Lobati 评论 - 看起来你可能最好使用 reset_session [比 session.clear],因为它做了一些超出 session.clear 的清理工作。在内部, reset_session 调用 session.destroy它本身也调用 clear 以及其他一些东西。

回答by vladCovaliov

To clear only certain parameters, you can use:

要仅清除某些参数,您可以使用:

[:param1, :param2, :param3].each { |k| session.delete(k) }

回答by vjnan369

to delete a user's session

删除用户的会话

session.delete(:user_id)

回答by David Mesaros

add this code to your ApplicationController

将此代码添加到您的 ApplicationController

def reset_session
  @_request.reset_session
end

( Dont know why no one above just mention this code as it fixed my problem ) http://apidock.com/rails/ActionController/RackDelegation/reset_session

(不知道为什么上面没有人提到这段代码因为它解决了我的问题) http://apidock.com/rails/ActionController/RackDelegation/reset_session