Rick
Rick

Reputation: 8846

Present subset of an object with ActiveModel Serializer

I am using ActiveModel Serializers in a Rails project.

The default serializer for the object is fairly large, and nesting an object in API responses result in rather large JSON objects.

Sometimes, I want to embed an object, but only need a small subset of the object's attributes to be present in the JSON.

Obviously, I could do something like this:

render json: @user, serializer: SmallerUserSerializer

but that would lead to a lot of duplication.

Is there an option that I can pass to the serializer so that it will only include a subset of the serializers attributes? Eg:

class BlogSerializer # This is pseudocode. Does not actually work. has_one :user, only_show: [:user_id, :profile_url] end

Upvotes: 1

Views: 1220

Answers (3)

Mohamed Abd El Rahman
Mohamed Abd El Rahman

Reputation: 293

Create a method and call to_json on the user object. Then add that method name to your list of attributes. The method can be called user also.

class BlogSerializer
  require 'json'
  attributes :id, :user

  def user
    JSON.parse "#{object.user.to_json( only: [ :id, :profile_url ] )}"
  end
end

Upvotes: 0

Vedant Agarwala
Vedant Agarwala

Reputation: 18819

Use the active model serialzers gem.

Your pseudo code will become the following simple modularized code:

class BlogSerializer < ActiveModel::Serializer
  attributes :user_id, :profile_url
end

Guide: http://railscasts.com/episodes/409-active-model-serializers

Upvotes: 0

kendotwill
kendotwill

Reputation: 2020

Create a method and call to_json on the user object. Then add that method name to your list of attributes. The method can be called user also.

class BlogSerializer
  attributes :id, :user

  def user
    object.user.to_json( only: [ :id, :profile_url ] )
  end
end

Upvotes: 0

Related Questions