搜尋

首頁  >  問答  >  主體

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
黄舟黄舟2861 天前912

全部回覆(1)我來回復

  • 巴扎黑

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

    devise 文件裡是這麼寫的
    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
    

    ================================
    至於在model中,一種直接點的方式是直接在方法中傳入user的實例或是id

    redmine的處理方法我比較喜歡
    User.rb

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

    然後在登入方法中

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

    最終在任何地方都可以呼叫User.current來取得目前登入者的實例

    devise其實我沒有深入用過,不太清楚他具體實現。
    剛好好奇心起,晚上再回去試試

    回覆
    0
  • 取消回覆