How return role name in has_many association at response of a resourcify model?

168 views Asked by At

My app uses rolify to manage multiple roles. I have correct configure the associations, but I need add the role name at the response of dispute.users.

Take a look at my associations bellow:

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

At this moment the response is something like this:

[
  {
    "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?
  }
]

My database table roles:

enter image description here

1

There are 1 answers

0
Gabriel Givigier On BEST ANSWER

You may use something to serialize the object like ActiveModelSerializer(https://github.com/rails-api/active_model_serializers)

So you just need to create the UserSerializer like this:

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

  def roles
    object.roles.pluck(:name)
  end
end