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

 乾岳_349 发布于 2022-10-26 22:28

想要做一个操作日志记录执行过的操作,
然后想在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
1 个回答
  • 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其实我没有深入用过,不太清楚他具体实现。
    正好好奇心起,晚上回去尝试一下

    2022-10-27 01:34 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有