Ruby on rails 在ActiveModel::Serializer中包含当前用户
我有一个只使用api的rails应用程序,它使用Ruby on rails 在ActiveModel::Serializer中包含当前用户,ruby-on-rails,serialization,active-model-serializers,Ruby On Rails,Serialization,Active Model Serializers,我有一个只使用api的rails应用程序,它使用active\u model\u序列化程序0.10。我在我的ApplicationController中有一个current\u user属性,我正试图从我的序列化程序访问它,以限制显示的数据。我可以像下面这样手动将其传递给作用域ExerciseSerializer.new(@exercise,scope:current_user),但我希望有一个通用的解决方案 这是我的应用程序控制器: class ApplicationController &l
active\u model\u序列化程序0.10。我在我的ApplicationController
中有一个current\u user
属性,我正试图从我的序列化程序访问它,以限制显示的数据。我可以像下面这样手动将其传递给作用域ExerciseSerializer.new(@exercise,scope:current_user)
,但我希望有一个通用的解决方案
这是我的应用程序控制器
:
class ApplicationController < ActionController::API
include Response
include ExceptionHandler
serialization_scope :view_context
# called before every action on controllers
before_action :authorize_request
attr_reader :current_user
def check_access_rights(id)
@current_user.id == id
end
def check_admin_rights
if !@current_user.admin
raise(ExceptionHandler::AuthenticationError, Message.unauthorized)
end
end
private
# Check for valid request token and return user
def authorize_request
@current_user = (AuthorizeApiRequest.new(request.headers).call)[:user]
end
end
序列化时出现以下错误:
** Module::DelegationError Exception: ExerciseSerializer#current_user delegated to scope.current_user, but scope is nil:
*** NameError Exception: undefined local variable or method `current_user' for #<ExerciseSerializer:0x007ff15cd2e9c0>
当我尝试从序列化程序中访问当前用户
时,出现以下错误:
** Module::DelegationError Exception: ExerciseSerializer#current_user delegated to scope.current_user, but scope is nil:
*** NameError Exception: undefined local variable or method `current_user' for #<ExerciseSerializer:0x007ff15cd2e9c0>
***NameError异常:未定义的局部变量或方法“当前用户”#
显然,范围是nil
任何想法都会有帮助。谢谢 在无数次阅读官方文档失败后随机发现:
这是有趣的部分:
def当前用户是所有者
范围==对象
结束
因此,默认情况下,当前用户保存在范围变量中,您不需要在控制器中添加代码来检索它
在0.10中工作,从0.08开始提供: