MVC – Are Session Aware Models a Bad Thing?

mvcruby-on-railssession

I'm thinking specifically in Rails here, but I suspect this is a wider question.

In a Rails web application I'm using data from the session in models in order that the models know who is logged in. I use this in a method which filters out some data from the database depending on a very simple permissions system.

The thing is: using sessions in models in Rails requires a bit of a workaround. It works, but I've a feeling that it's something that I shouldn't be doing and I'm worried there's a big gotcha I'm missing.

I suppose the Right Thing To Do would be to return all the data and filter out the not-wanted bits in the controller before passing that to the view, but doing it in the model seems to avoid quite a bit of code duplication and so feels "cleaner."

Can anyone tell me why or shouldn't do this? Or that it's not a problem?

Best Answer

I can't tell from a "should" or "should not" perspective. It breaks the MVC model to some extend.

Then on the other side your model is responsible to generate the most efficient business logic and database query possible. So letting the controller sort data by permission is not the way to solve this issue (it should never get any data the actual user is not allowed to see for security reasons). So this may be even worse than accessing the session in the model.

In my opinion (and how I would implement it if possible) I would add some special methods that take the user information as params (like def show_orders(current_user)) and return the results. That way you can keep the session handling in the controller (relevant if later you decide to use the model for another web interface or whatever) and still have optimized access.

Or add the access permission handling to the User model so you can access them like current_user.orders. If it's really simple permissions, you may be able to add this to the has_many declarations in Rails. Otherwise add some methods there.