0

I have Organization serializer as follow:

class OrganizationSerializer < ActiveModel::Serializer
  attributes :user_first_name, 
             :user_last_name,
             :user_email

  has_many :user

  def user_first_name
    object.user.first_name
  end

  def user_last_name
    object.user.last_name
  end

  def user_email
    object.user.email
  end

end

My question, is there a better way not to repeat def user_... for each attribute definition?

Akadisoft
  • 306
  • 1
  • 2
  • 13
  • An entirely different (could be better) way would be to nest a user object under organization. and use AMS's associations. So UserSerializer takes care of `:first_name, :last_name, :email`. And organization ends up with a `user` key. – Leonel Galán Feb 11 '16 at 16:19

1 Answers1

0

In my opinion, the best course of action would be to do it like the snippet below:

has_many :users, each_serializer: YourUserSerializer

Another option would be:

attributes :users

def users
  ActiveModel::ArraySerializer.new(object.users, each_serializer: YourUserSerializer)
end

This allows you to get back an array of objects in your JSON response and have the option to serialize them as well.

If you're not looking to serialize the users (seems like you'd want to, and really it is proper to), then pass false to the each_serializer option.

Either of the above solutions would produce something like this (i'm filling in the gaps):

{
  "organization": {
    "users": [{
      "first_name": "John",
      "last_name": "Doe",
      "email": "johndoe@gmail.com"
    }]
  }
}
Noah
  • 390
  • 1
  • 3
  • 15