2013-03-28 58 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架構的規則。