user1576738
user1576738

Reputation: 121

getting current_user in any model in rails

I am trying to get the current_user value into a model. I know that this is probably not appropriate since models should be kept secluded from this type of interaction but I'm running into a problem. I need to include a current_user within a method in a model and do not know how to do it.

I need to make this happen on an update in my stage controller and pass the current_user to the stage model and have that current_user value available. Any help is appreciated.

def update
  if @stage.update_attributes(params[:stage])
   redirect_to [@project, @stage], :notice => 'Stage was successfully updated.'
  else
   render :action => "edit"
  end
end

Upvotes: 0

Views: 382

Answers (1)

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

You could also store the current user into Thread.current's hash.

See http://rails-bestpractices.com/posts/47-fetch-current-user-in-models

class User < ActiveRecord::Base
  def self.current
    Thread.current[:user]
  end
  def self.current=(user)
    Thread.current[:user] = user
  end
end

Upvotes: 1

Related Questions