Rails中在model中获取当前登录用户

应用场景:更新系统操作记录时,记录操作人即当前登录用户

方法一:在线程中添加一个变量

class UsersController < ApplicationController
  before_action :set_current_user_to_thread, only: [:create, :update]

  private
  def set_current_user_to_thread
    Thread.current[:user] = User.find(session[:id])
  end
end

class User < ActiveRecord::Base
  def current_user
    Thread.current[:user]
  end
end

方法二:在model中添加一个类变量

class User < ActiveRecord::Base  
  cattr_accessor :current_user  

end  
class UsersController < ApplicationController
before_action: :set_current_user, only: [:create, :update]

private
def set_current_user
User.current_user = User.find(session[:id]
end
end

 

转载于:https://www.cnblogs.com/xiaoff/p/9052396.html

你可能感兴趣的:(Rails中在model中获取当前登录用户)