开发者

Visibility of session variable in 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 c开发者_JAVA技巧ontroller 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.

Thanks


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 on Wikipedia
  • Rails Guides

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜