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.
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.