search

Home  >  Q&A  >  body text

ruby - 怎么在model里边获取当前用户的ID等信息

想要做一个操作日志记录执行过的操作,
然后想在model里边获取当前操作用户的ID,进行操作的数据表名称,还有操作类型
现在写了一个moduel。

module RecordOperation
  extend ActiveSupport::Concern
  included do
    after_update :record_operation
    before_destroy :record_operation
    after_create :record_operation
    def record_operation

    end
end
黄舟黄舟2777 days ago853

reply all(1)I'll reply

  • 巴扎黑

    巴扎黑2017-04-22 08:58:27

    This is what the design document says
    To verify if a user is signed in, use the following helper:

    user_signed_in?
    

    For the current signed-in user, this helper is available:

    current_user
    

    You can access the session for this scope:

    user_session
    

    ================================
    As for the model, a direct way is to directly pass in the user instance or id in the method

    I like redmine’s processing method better
    User.rb

    def self.current=(user)
        Thread.current[:current_user] = user
    end
    
    def self.current
      Thread.current[:current_user] ||= User.anonymous
    end
    

    Then in the login method

    User.current = find_current_user
    if user && user.is_a?(User)
      User.current = user
      start_user_session(user)
    else
      User.current = User.anonymous
    end
    

    Finally User.current can be called anywhere to get an instance of the currently logged in person

    In fact, I have not used design in depth, and I am not sure about its specific implementation.
    I just got curious, so I will try it when I go back tonight

    reply
    0
  • Cancelreply