2014-06-30 79 views
0

因此,我正在进行一种RoR应用程序的自定义滚动历史记录。我挂断的部分是获取登录的用户信息与记录绑定。我想通过一个附属于ActionController::Base类的子模块来获取用户。问题是,我无法从子模块中检索它。如何访问子模块的属性

这里是我的代码:

module Trackable 


    # This is the submodule 
    module TrackableExtension 

    extend ActiveSupport::Concern 
    attr_accessor :user 

    included do 
     before_filter :get_user 
    end 

    def get_user 
     @user ||= current_user # if I log this, it is indeed a User object 
    end 
    end 




    # Automatically call track changes when 
    # a model is saved 
    extend ActiveSupport::Concern 
    included do 
    after_update :track_changes 
    after_destroy :track_destroy 
    after_create :track_create 
    has_many :lead_histories, :as => :historical 
    end 


    ### --------------------------------------------------------------- 
    ### Tracking Methods 

    def track_changes 
    self.changes.keys.each do |key| 
     next if %w(created_at updated_at id).include?(key) 

     history = LeadHistory.new 
     history.changed_column_name = key 
     history.previous_value = self.changes[key][0] 
     history.new_value = self.changes[key][1] 
     history.historical_type = self.class.to_s 
     history.historical_id = self.id 
     history.task_committed = change_task_committed(history) 
     history.lead = self.lead 

     # Here is where are trying to access that user. 
     # @user is nil, how can I fix that?? 
     history.user = @user 

     history.save 
    end 
    end 

在我的模型,然后它的那样简单:

class Lead < ActiveRecord::Base 
    include Trackable 
    # other stuff 
end 
+0

你是如何将这个包含在你的模型中的? – San

+0

以上更新.. –

+0

是否有一个原因,你为什么使用子模块?我认为子模块内的所有代码都可以直接在主模块中工作。 – San

回答

0

我得到这个通过设置Trackable模块变量工作。

在我TrackableExtension::get_user方法我做了以下内容:

def get_user 
    ::Trackable._user = current_user #current_user is the ActionController::Base method I have implemented 
end 

然后为Trackable模块我说:

class << self 
    def _user 
     @_user 
    end 

    def _user=(user) 
     @_user = user 
    end 
end 

然后,在任何Trackable方法我可以做一个Trackable::_user并得到正确的价值。