2013-03-28 57 views
1

您好我想访问模型中的current_user用于通过find_or_create_by动态创建元素。在模型中访问设计current_user

以下是我的模型

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 #<Event:0x007fb575e92000> 
+2

您无法访问模型中的current_user。您需要将current_user传递给来自控制器的方法。 – Dogbert 2013-03-28 11:25:40

回答

3

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 
3

访问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架构的规则。