Ruby-on-rails 从控制器中删除 Cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6104090/
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
Deleting Cookies from a Controller
提问by Dex
I set some cookie values in my form using jQuery. I can read them just fine in my Rails controller via the cookiesmethod. When I call cookies.delete(:my_key), they appear to be gone when I call cookiesagain. But when I reload the page, the cookies are back again.
我使用 jQuery 在我的表单中设置了一些 cookie 值。我可以通过cookies方法在我的 Rails 控制器中很好地读取它们。当我打电话时cookies.delete(:my_key),当我cookies再次打电话时,它们似乎消失了。但是当我重新加载页面时,cookie 又回来了。
Is there a way to delete the cookies for good from inside my controller?
有没有办法从我的控制器内部永久删除 cookie?
EDIT
编辑
This is very strange since I'm looking at the response headers and they seem to be deleting the cookie. Maybe it's because it is a 302 request?
这很奇怪,因为我正在查看响应头,他们似乎正在删除 cookie。也许是因为它是一个 302 请求?
Set-Cookie: my_key=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT
回答by Rubyist
For example, your cookie look like this
例如,您的 cookie 看起来像这样
cookies[:foo] = {:value => 'bar', :domain => '.text.com'}
As you tried this one => cookies.delete :foo
当你尝试这个时 => cookies.delete :foo
The logs will say => Cookie set: foo=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT
日志会说 => Cookie set: foo=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT
Notice that the domain is missing. Tried this way
请注意,缺少域。试过这种方法
cookies.delete :foo, :domain => '.text.com'
cookies.delete :foo, :domain => '.text.com'
Function = >
功能 = >
# Removes the cookie on the client machine by setting the value to an empty string
# and setting its expiration date into the past. Like []=, you can pass in an options
# hash to delete cookies with extra data such as a +path+.
def delete(name, options = {})
options.stringify_keys!
set_cookie(options.merge("name" => name.to_s, "value" => "", "expires" => Time.at(0)))
end

