在rails中的任何模型中获取current_user

时间:2012-11-13 20:05:33

标签: ruby-on-rails model

我试图将current_user值转换为模型。我知道这可能不合适,因为模型应该与这种类型的交互保持隔离,但我遇到了问题。我需要在模型中的方法中包含current_user,但不知道如何操作。

我需要在我的舞台控制器的更新中实现这一点,并将current_user传递给舞台模型并使current_user值可用。任何帮助表示赞赏。

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

1 个答案:

答案 0 :(得分:1)

您还可以将当前用户存储到Thread.current的哈希中。

请参阅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