Reputation: 12759
I set some cookie values in my form using jQuery. I can read them just fine in my Rails controller via the cookies
method. When I call cookies.delete(:my_key)
, they appear to be gone when I call cookies
again. But when I reload the page, the cookies are back again.
Is there a way to delete the cookies for good from inside my controller?
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?
Set-Cookie: my_key=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT
Upvotes: 45
Views: 47242
Reputation: 2927
We can delete the cookies by passing name and options to delete
method as follows:
Syntax: delete(name, options = {})
Description: Removes the cookie on the client machine by setting the value to an empty string and the expiration date in the past. Like []=, you can pass in an options hash to delete cookies with extra data such as a :path.
Example:
cookies.delete('JWT', {
value: "",
expires: 1.day.ago,
path: '/api'
})
Upvotes: 0
Reputation: 6542
For example, your cookie look like this
cookies[:foo] = {:value => 'bar', :domain => '.text.com'}
As you tried this one => cookies.delete :foo
The logs will say => 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'
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
Upvotes: 49