Rails: Access to current_user from within a model in Ruby on Rails

I’d say your instincts to keep current_user out of the model are correct.

Like Daniel I’m all for skinny controllers and fat models, but there is also a clear division of responsibilities. The purpose of the controller is to manage the incoming request and session. The model should be able to answer the question “Can user x do y to this object?”, but it’s nonsensical for it to reference the current_user. What if you are in the console? What if it’s a cron job running?

In many cases with the right permissions API in the model, this can be handled with one-line before_filters that apply to several actions. However if things are getting more complex you may want to implement a separate layer (possibly in lib/) that encapsulates the more complex authorization logic to prevent your controller from becoming bloated, and prevent your model from becoming too tightly coupled to the web request/response cycle.

Leave a Comment