2016-12-31 56 views
1

我的應用使用rolify來管理多個角色。我有正確的配置關聯,但我需要在dispute.users的響應中添加角色名稱如何在資源模型的響應中返回has_many關聯中的角色名稱?

在我協會看一看波紋管:

class Dispute < ApplicationRecord 
    resourcify 

    has_many :users, through: :roles 

    ... 
end 

class UsersRole < ApplicationRecord 
    belongs_to :user 
    belongs_to :role 
end 

class User < ApplicationRecord 
    ... 

    rolify 

    has_many :users_roles 
    has_many :roles, through: :users_roles 
    has_many :disputes, through: :roles, source: :resource, source_type: 'Dispute' 

    ... 
end 

此時的反應是這樣的:

[ 
    { 
    "id": "90301da1-5ab6-4834-9865-30dc678043f1", 
    "cpf": "11201300266", 
    "name": "Convidado", 
    "email": "[email protected]" 
    "role": "guest" <<< This not exists yet! How add this column on response? 
    } 
] 

我的數據庫表roles

enter image description here

回答

1

你可以使用一些東西來序列化這個對象CT像ActiveModelSerializer(https://github.com/rails-api/active_model_serializers

所以你只需要創建UserSerializer這樣的:

class SomeSerializer < ActiveModel::Serializer 
    attributes :id, :cpf, :name, :email, :roles 

    def roles 
    object.roles.pluck(:name) 
    end 
end 
相關問題