Question

Looking for the best way to do ownership validation in a Rails model without bloating my controllers. This means I need to pass the current_user to the model somehow.

I'm currently setting a class attribute on the User model to the current_user at the beginning of every request:

class User < ActiveRecord::Base
  cattr_accessor :current_user
end

class ApplicationController < ActionController::Base
   before_filter :set_current_user
   def set_current_user
     User.current_user = current_user
   end
end

I'm not sure if I fully understand the lifetime of User.current_user in this scenario. Is it possible the value could change during the request?

I primarily want to know if the above is safe to use, and also if there is a better approach.

Was it helpful?

Solution

To answer the first part of your question. The attribute will be saved in memory untill the User-class gets flushed/sent to garbage collector. That's usually when the VM or interpreter shuts down.

In an environment like Heroku, this variable can be stored between requests and an unauthenticated user will have access to the most recent user by accessing this variable, unless it's cleared out when the first user is done.

OTHER TIPS

This is definitely the correct approach if you want to conform to best practices. current_user is a controller method, and by following the Chain-of-responsibility pattern the User model should not know who the current user is.

This is not a safe approach:) Keep your state in the controllers, and business logic within the models.

If the current_user needs to be passed to the model layer, then the model shouldn't care about who this is. You could always use associations for filtering access to content.

current_user.widgets.find(params[:id])

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top