2016-12-31 7 views
1

내 앱은 rolify을 사용하여 여러 역할을 관리합니다. 연결을 올바르게 구성했지만역할 이름을 dispute.users의 응답에 추가해야합니다.resourcify 모델의 응답으로 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

당신은 obje를 직렬화하기 위해 무언가를 사용할 수 있습니다. ActiveModelSerializer 같은 CT (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