在Ruby on Rails框架中,获取当前用户通常涉及到会话管理和身份验证。以下是一些常见的方法来在Model中获取当前用户:
在Rails中,可以使用Thread.current
来存储和访问当前线程的用户信息。
# 在Controller中设置当前用户
class ApplicationController < ActionController::Base
before_action :set_current_user
private
def set_current_user
Thread.current[:current_user] = current_user
end
end
# 在Model中获取当前用户
class SomeModel < ApplicationRecord
def current_user
Thread.current[:current_user]
end
end
可以在ApplicationController中定义一个实例方法来获取当前用户,并在需要的地方调用。
# 在ApplicationController中定义实例方法
class ApplicationController < ActionController::Base
helper_method :current_user
private
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
end
# 在Model中调用
class SomeModel < ApplicationRecord
def current_user
controller.current_user
end
end
原因:Rails的Model层不应该直接依赖于Controller或Session,这违反了关注点分离的原则。
解决方法:
# 创建一个Service对象
class CurrentUserService
def self.call
Thread.current[:current_user]
end
end
# 在Model中使用Service对象
class SomeModel < ApplicationRecord
def current_user
CurrentUserService.call
end
end
通过以上方法,你可以在Ruby on Rails的Model中获取当前用户,并确保代码的可维护性和安全性。
领取专属 10元无门槛券
手把手带您无忧上云