在模型中访问devise current_user

您好我正在尝试访问模型中的current_user,以便使用find_or_create_by动态创建元素。

以下是我模型中的方法

def opponent_name=(name) self.opponent = Opponent.find_or_create_by_name_and_team_id(name,current_user.team_id) if name.present? end 

但我得到的错误是

 NameError in EventsController#create undefined local variable or method `current_user' for # 

无法从Rails中的模型文件中访问current_user ,只能访问控制器,视图和帮助程序。

你应该做的是将current_user.team_id传递给opponent_name方法,如下所示:

 def opponent_name=(name, current_user_team_id) self.opponent = Opponent.find_or_create_by_name_and_team_id(name,current_user.team_id) if name.present? end 

访问模型文件中的current_user:

 # code in Applcation Controller: class ApplicationController < ActionController::Base before_filter :global_user def global_user Comment.user = current_user end end #Code in your Model File : class Comment < ActiveRecord::Base cattr_accessor :user # it's accessible outside Comment attr_accessible :commenter def assign_user self.commenter = self.user.name end end 

请原谅,如果它违反任何MVC架构规则。

它不是访问模型中current_user的好方法,这个逻辑属于控制器。 但是,如果你真的无法找到一个解决方法,你应该把它放到一个线程中。 但请记住,这不是它应该如何构建的方式。

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