[英]In Rails 5, how access cookies method in a model or helper?
How does one access cookies inside a Rails model or helper?如何访问 Rails 模型或助手中的 cookie?
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.试图干掉一些控制器方法,我试图将多个控制器调用移动到 cookie() 到 application_helper.rb 和/或模型中。
What doesn't work in application_helper.rb:什么不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'所有这些都会导致未定义的方法“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.注意:简单地反驳 MVC 教条的善意答案被错误地放在这里......我已经设计了足够长的时间(几十年)来知道什么时候在 MVC 线之外着色(如果可能)是更好的路线。 But the precise syntax eludes me even after digging through Rails source.但是即使在挖掘 Rails 源代码之后,我也无法理解精确的语法。 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).这个问题是由一个有点复杂的情况引起的,其中涉及跨域、ajax 环境中 cookie 的浏览器处理不一致,有时包括本地文件(Chrome 拒绝管理 cookie)。
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
.这不是一个好主意 :) 模型是类,它们不应该知道 Web 级别上发生了什么,这就是为什么在ActionController
实现了cookies
方法,但在ActionModel
或ActionHelper
没有这样的实现。 If you need a cookie value in a model, pass a value from a controller then.如果您需要模型中的 cookie 值,则从控制器传递一个值。 This is how it should be done.这是应该如何做的。
As @Vasili mentioned, cookies
is only available in controllers.正如@Vasili 提到的, cookies
只在控制器中可用。 But if you want to access cookies
in helpers or models, just pass it as an argument, for example:但是如果你想访问助手或模型中的cookies
,只需将其作为参数传递,例如:
helper example:助手示例:
module ApplicationHelper
def some_helper(given_cookies)
given_cookies[:foo] = 'bar'
end
end
In view:鉴于:
<%= some_helper(cookies) %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.