What is the difference between request.cookies and cookies in a controller?
request.cookies
is a Rack provided method. It is just a hash of key value pairs, obtained by parsing the cookie header.
The controller cookies
method returns request.cookie_jar
. The cookie jar is built from the exact same request.cookies
data, but parses it adds a bunch of rails functionality on top, such as signed cookies, serialising data into cookies etc.
I can't see any reason why a key would be present in one, but not the other.
Ideally, request.cookies
and cookies
should be the same. However, in POST (create action) requests, rails verifies the XSRF token. If that verification fails, the cookies from request.cookies
are not available in the request.cookie_jar
. Which means, they are not available via the cookies
method.
To identify if the cookies mismatch is because of the XSRF token missing. In your request, try to identify the class of your cookie hash. cookies.hash
should return you ActionDispatch::Cookies::CookieJar
. If it instead returns ActionController::RequestForgeryProtection::ProtectionMethods::NullSession::NullCookieJar
, you have a XSRF token mismatch.
This scenario is likely to happen when you make these calls via javascript which don't by default pick the XSRF token and send with the request. See the answer here: https://stackoverflow.com/a/8175979/976880 to learn how to fix it.