ruby - 怎么在model里边获取当前用户的ID等信息
黄舟
黄舟 2017-04-22 08:56:27
[Ruby讨论组]

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号