Rails 中会话变量的可见性 [英] Visibility of session variable in rails

查看:46
本文介绍了Rails 中会话变量的可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下 Rails 中会话变量的可见性.我的意思是会话变量将在哪些类中可用.我能够访问控制器中的会话变量,但是如果我创建一个独立的类,我将无法访问会话哈希.还让我知道在独立类中访问会话变量的最佳方法是什么.有人可以帮我理解这个会话概念吗?任何与此相关的指示或阅读资料都会有所帮助.

Can someone explain me the visibility of the session variable in Rails. I mean across what classes will the session variables be available. I am able to access the session variable in the controller but if I create a standalone class, I am not able to access the session hash. Also let me know what is the best way to access the session variable in a standalone class. Can someone help me understand this session concept?? Any pointers or reading related to this will be helpful.

谢谢

推荐答案

您只能在控制器中访问会话数据,这是因为它是每个 MVC 应该可以访问的唯一地方.控制器从字面上控制当前会话和请求,然后检索并向模型和视图发送必要的信息.

You can only access session data in the controllers, this is because it's the only place it should be accessible per MVC. The controller literally controls the current session and request, and then retrieves and sends the necessary information to the model and view.

如果您需要在其他地方访问它,请将所需数据作为参数传递给控制器​​调用中所需的方法.

If you need to access it elsewhere, pass the needed data as a parameter to the desired method in a call from your controller.

这里有一些资源可以了解有关模型-视图-控制器设计模式的更多信息:

Here are some resources to learn more about the Model-View-Controller design pattern:

使用 MVC 的全部意义在于保持应用程序的各个不同部分分离和隔离.这允许您拥有更易于修改的更有组织的代码.虽然有一些方法可以绕过 Rails 严格的 MVC 实现并使用它们通常不会使用的东西,但建议不要这样做.约定俗成是有原因的,如果您想打破常规,请退后一步,想想如何在不这样做的情况下使其工作,最终您将拥有更好的代码.

The whole point of using MVC is to keep the various different parts of your application separated and isolated. This allows you to have more organized code that is easier to modify. While there are ways to get around Rails' strict MVC implementation and use things where they wouldn't conventionally be used, this is advised against. The conventions are there for a reason, if you're thinking of breaking take a step back and think of how to make it work without doing so and you'll end up having better code.

这篇关于Rails 中会话变量的可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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