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

浏览:39日期:2022-10-20

问题描述

想要做一个操作日志记录执行过的操作, 然后想在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 endend

问题解答

回答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] = userenddef self.current Thread.current[:current_user] ||= User.anonymousend

然后在登录方法中

User.current = find_current_userif user && user.is_a?(User) User.current = user start_user_session(user)else User.current = User.anonymousend

最终在任何地方都可以调用User.current来获取当前登录者的实例

devise其实我没有深入用过,不太清楚他具体实现。正好好奇心起,晚上回去尝试一下

相关文章: