在Rails 5中,如何访问模型或助手中的cookie方法? [英] In Rails 5, how access cookies method in a model or helper?

查看:68
本文介绍了在Rails 5中,如何访问模型或助手中的cookie方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Rails模型或帮助器中访问cookie?

How does one access cookies inside a Rails model or helper?

试图使某些控制器方法变干,我试图将多个控制器调用移至cookies()

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.

在application_helper.rb中什么不起作用

What doesn't work in application_helper.rb:

cookies[:foo]
ActionDispatch::Cookies.cookies[:foo]
ActionController.cookies[:foo]
ActionDispatch::Cookies::ChainedCookieJars.cookie[:foo]

所有这些都导致未定义的方法' Cookies'

All of which result in undefined method 'cookies'

注意:原本只是反流MVC教义的好意答案在这里放置不当...我设计了足够长的时间(数十年),以了解何时在外面着色MVC线(如果可能)是更好的方法。但是即使在深入了解Rails源代码之后,精确的语法仍使我难以理解。这个问题是由某种复杂情况引起的,这种情况尤其涉及跨域ajax环境中浏览器对Cookie的不一致处理,该环境有时包括本地文件(Chrome拒绝管理cookie)。

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).

推荐答案

这不是一个好主意:)模型是类,他们不应该知道网络上正在发生什么级别,这就是为什么 cookies 方法在 ActionController 中实现的原因,但是在中没有这样的实现ActionModel ActionHelper 。如果您需要模型中的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. If you need a cookie value in a model, pass a value from a controller then. This is how it should be done.

这篇关于在Rails 5中,如何访问模型或助手中的cookie方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆