How to get current_user in model observer?

Given the following models:

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

When the room name is updated, I want to create a RoomFeed element, showing who the user is, who made the update.

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

The problem is in my observer for RoomFeed:

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

I cannot get the user.id of the person who just made the update. How should I do it? is there a better way to do an update to get current_user?

+5
source share
5 answers

, , room.updated_by . _by, attr_accessor. , , , current_user _by, .

+5

"".

_ , Room . , RoomManager , ...

(Non persistant) Room.rb current_user....

# room.rb
class Room
  attr_accessor :room_tagger_id
end

current_user @room.

!

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

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.  

, , --, , -, .nil?

+2

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 . .

-3

All Articles