Skip to main content
Ask A Question
Notifications
You’re not receiving notifications from this thread.
Subscribe

How return has_many with array instead of object

General • Asked by Bruno Wego

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

Thanks Chris Oliver, It is exactly I want!


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

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 30,005+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.