How return has_many with array instead of object
Have a way to a "has_many" return a array instead of object?
class UserSerializer < ActiveModel::Serializer
attributes :id, :name, :nickname, :image, :roles
has_many :roles
end
See my return bellow:
{
"id": 2,
"name": "Administrador",
"nickname": "admin",
"image": null,
"roles": [
{
"name": "admin"
},
{
"name": "member"
}
]
}
We chatted in Slack about this and our solution was to use a custom method here in the serializer to build the output as an array of strings rather than an array of objects.
class UserSerializer < ActiveModel::Serializer
attributes :role_names
def role_names
object.roles.map(&:name)
end
end
For convention I have alter to uppercase the role names, see below:
class UserSerializer < ActiveModel::Serializer
attributes :id, :name, :nickname, :image, :roles
def roles
object.roles.map { |role| role.name.upcase }
end
end