我的应用使用rolify来管理多个角色。我已正确配置关联,但我需要在dispute.users
的响应中添加角色名称。
看看下面我的协会:
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": "convidado@gmail.com"
"role": "guest" <<< This not exists yet! How add this column on response?
}
]
我的数据库表roles
:
答案 0 :(得分:1)
您可以使用某些内容来序列化对象,如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