How to get the current_user in a model observer?

前端 未结 5 2016
有刺的猬
有刺的猬 2021-01-13 05:35

Given the following models:

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

When a Room title is updated, I want to c

5条回答
  •  悲哀的现实
    2021-01-13 06:10

    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?

提交回复
热议问题