How to get the current_user in a model observer?

左心房为你撑大大i 提交于 2019-12-01 05:26:02

I think what you are looking for is, room.updated_by inside your observer. If you don't want to persist the updated_by, just declare it as an attr_accessor. Before you push the update, make sure you assign the current_user to updated_by, may be from you controller.

This is a typical "separation of concern" issue.

The current_user lives in the controller and the Room model should know nothing about it. Maybe a RoomManager model could take care of who's changing the name on the doors...

Meanwhile a quick & dirty solution would be to throw a (non persistant) attribute at Room.rb to handle the current_user....

# room.rb
class Room
  attr_accessor :room_tagger_id
end

and pass your current_user in the params when updating @room.

That way you've got the culprit! :

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

Create the following

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

Then use...

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

Remember that the value isn't guaranteed to be set when your class is called from non-web requests, like rake tasks, so you should check for .nil?

Update user.rb

class User < ActiveRecord::Base
  cattr_accessor :current
end

Update application_controller.rb

class ApplicationController
  before_filter :set_current_user

  private
  def set_current_user
    User.current = current_user
  end
end

Then you can get logged user by User.current anywhere. I'm using this approach to access user exactly in observers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!