我只需要为当前经过身份验证的用户输出 auth_token 属性。
我的用户控制器有
class Api::V1::UsersController < ApplicationController
before_action :authenticate_with_token!, only: [:show, :create, :update, :destroy]
respond_to :json
def show
authorize User
respond_with User.find(params[:id])
end
...
序列化器:
class UserSerializer < ActiveModel::Serializer
attributes :id, :email, :created_at, :updated_at, :auth_token
has_one :role
http 请求是这样的: 获取 http://api.domain.com/users/1 带有标头:接受、内容类型和授权 (授权是 auth_token)。
返回的是:
{
"user": {
"id": 1,
"email": "[email protected]",
"created_at": "2015-12-01T07:36:55.276Z",
"updated_at": "2015-12-01T07:36:55.276Z",
"auth_token": "8xxoZjZyx313cx2poabz",
"role": {
"id": 1,
"name": "admin",
"created_at": "2015-12-01T07:36:55.190Z",
"updated_at": "2015-12-01T07:36:55.190Z"
}
}
}
如果它所属的用户请求它或具有
auth_token
角色的用户请求它,我只希望显示super
。我的用户模型中有一个方法可以检查像 has_role? :super
. 这样的角色
在序列化程序中,我已经尝试过这个,但它实际上只是在黑暗中拍摄。我不知道如何做到这一点:
...
def filter(keys)
if scope.auth_token == :auth_token
keys
else
keys - [:auth_token]
end
end
使用 active_model_serializer 版本 0.9.3
在源代码中看到this,我脑子里闪过一些东西。
将上面的
filter
方法更改为以下方法给了我想要的结果。
def filter(keys)
if (scope == object) or scope.has_role?(:super)
keys
else
keys - [:auth_token]
end
end
希望这可以帮助其他使用 0.9.x 版本的人
在你的序列化器中,即使
:auth_token
是一个字段,你应该能够用同名的方法覆盖它。所以;
class UserSerializer < ActiveModel::Serializer
attributes :id, :email, :created_at, :updated_at, :auth_token
has_one :role
def auth_token
object.auth_token == scope.auth_token || scope.has_role?(:super) ? object.auth_token : nil
end
end