Ask A Question

Notifications

You’re not receiving notifications from this thread.

How return has_many with array instead of object

Bruno Wego asked in General

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"
    }
  ]
}
Reply

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
Reply

Thanks Chris Oliver, It is exactly I want!

Reply

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
Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,946+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.