Reputation: 19247
How does one access cookies inside a Rails model or helper?
Trying to dry up some controller methods, I am trying to move multiple controller calls to cookies() into application_helper.rb and/or a model.
What doesn't work in application_helper.rb:
cookies[:foo]
ActionDispatch::Cookies.cookies[:foo]
ActionController.cookies[:foo]
ActionDispatch::Cookies::ChainedCookieJars.cookie[:foo]
All of which result in undefined method 'cookies'
Note: Well-meaning answers that simply regurgitate MVC dogma are mis-placed here... I've architected long enough (decades) to know when coloring outside the MVC lines (if possible) is the better route. But the precise syntax eludes me even after digging through Rails source. This question is prompted by a somewhat complex situation related to, among other things, inconsistent browser handling of cookies in cross-domain, ajax environment that sometimes includes local files (for which Chrome declines to manage cookies).
Upvotes: 4
Views: 5170
Reputation: 4538
As @Vasili mentioned, cookies
is only available in controllers. But if you want to access cookies
in helpers or models, just pass it as an argument, for example:
helper example:
module ApplicationHelper
def some_helper(given_cookies)
given_cookies[:foo] = 'bar'
end
end
In view:
<%= some_helper(cookies) %>
Upvotes: 1
Reputation: 905
It's not a good idea :) Models are classes, and they shouldn't be aware of what is happening on a web level, and that's why cookies
method is implemented in ActionController
, but there's no such implementation in ActionModel
or ActionHelper
. If you need a cookie value in a model, pass a value from a controller then. This is how it should be done.
Upvotes: 8