Access session in models

You can use after filters on your actions or similar methods to ensure that updates to the model occur after each action. The controller should call the model method to make any changes. This way the model can be used with multiple controllers and they are not coupled. Rails makes this type of best practice a hard boundary by not allowing models access to controller data except by the controller invoking model methods. The only other thing you could look into is observers. They have access to both the controller and model, but are only invoked when a change occurs to a model they are registered for.


Both of the above are correct.

An even easier answer to your question is that you should access the session in your controller, then pass that information into the model via a method.

HTH, Kevin Skoglund

Right, and furthermore, the decoupling of Controller and Model really should be absolute in any MVC system. Think of it this way. If you yanked the model objects out of the application and dropped them in another application (hypothetically), would they still work? If they were coupled with the session object they would not (just to be clear this hypotheical receiving application has no Session class). Your MVC breaks down at a fundamental level.

On the other hand it is generally more complicated to decouple Controller and View (yet not impossible). Most MVC based frameworks don't tent to attempt this decoupling. That being said, it is still good practice to make every effort to decouple even these.

Generally speaking, the Controller is the least reusable component of the MVC, since they tend to contain most of the code that is specifc to a particular application. Model objects on the other hand should be fully reuseable, requiring clear decoupling from the rest of the application code.