Ruby on rails 4 仅显示当前用户和特定角色的序列化程序属性
我需要仅为当前经过身份验证的用户输出auth_token属性 我的用户控制器Ruby on rails 4 仅显示当前用户和特定角色的序列化程序属性,ruby-on-rails-4,active-model-serializers,Ruby On Rails 4,Active Model Serializers,我需要仅为当前经过身份验证的用户输出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 U
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
...
我只想在它所属的用户请求或具有super
角色的用户请求时显示auth_令牌
。在我的用户模型中,我有一个方法可以检查角色,如has\u role?:超级
在连载程序中,我尝试过这一点,但实际上这只是一次冒险。我不知道如何做到这一点:
...
def filter(keys)
if scope.auth_token == :auth_token
keys
else
keys - [:auth_token]
end
end
编辑
使用active_model_serializer版本0.9.3时,在源代码中看到了一些东西,我的脑海中点击了一些东西
将上面的filter
方法更改为下面的方法可以得到所需的结果
def filter(keys)
if (scope == object) or scope.has_role?(:super)
keys
else
keys - [:auth_token]
end
end
希望这能帮助其他使用0.9.x版的人
...
def filter(keys)
if scope.auth_token == :auth_token
keys
else
keys - [:auth_token]
end
end
def filter(keys)
if (scope == object) or scope.has_role?(:super)
keys
else
keys - [:auth_token]
end
end