All threads / How return has_many with array instead of object

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

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
Join the discussion

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

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

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

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.