如何在模型观察器中获取current_user?

鉴于以下型号:

Room (id, title) RoomMembers (id, room_id) RoomFeed, also an observer 

当房间标题更新时,我想创建一个RoomFeed项目,显示用户是谁进行了更新。

 @room.update_attributes(:title => "This is my new title") 

问题在于我对RoomFeed的观察者:

 def after_update(record) # record is the Room object end 

我无法获得刚刚进行更新的人的user.id. 我该怎么做呢? 有没有更好的方法来进行更新,所以我得到current_user?

我认为你正在寻找的是,你的观察者内部是room.updated_by。 如果您不想保留updated_by,只需将其声明为attr_accessor即可。 在推送更新之前,请确保将current_user分配给updated_by,可能来自您的控制器。

这是典型的“关注分离”问题。

current_user存在于控制器中,而Room模型应该对它一无所知。 也许RoomManager模型可以照顾谁在改变门上的名字……

同时一个快速而肮脏的解决方案是在Room.rb上抛出一个(非持久的)属性来处理current_user ….

 # room.rb class Room attr_accessor :room_tagger_id end 

更新@room时,在params中传递current_user。

那样你就有罪魁祸首! :

 def after_update(record) # record is the Room object current_user = record.room_tagger_id end 

创建以下内容

 class ApplicationController before_filter :set_current_user private def set_current_user User.current_user = #however you get the current user in your controllers end end class User ... def self.current_user @@current_user end def self.current_user= c @@current_user = c end ... end 

然后使用……

 User.current_user wherever you need to know who is logged in. 

请记住,当从非Web请求(例如rake任务)调用类时,不保证设置该值,因此您应该检查.nil?

更新user.rb

 class User < ActiveRecord::Base cattr_accessor :current end 

更新application_controller.rb

 class ApplicationController before_filter :set_current_user private def set_current_user User.current = current_user end end 

然后,您可以在任何地方通过User.current获取登录用户。 我正在使用这种方法在观察者中完全访问用户。