0
class User < ActiveRecord::Base
  has_many :images
end
class Image < ActiveRecord::Base
  has_many :sub_images
  belongs_to :user
end
class SubImage < ActiveRecord::Base
  belongs_to :image
end

Routes

/users/:user_id
/users/:user_id/images/:image_id
/users/:user_id/images/:image_id/subimages/:subimage_id

resources :users do
  resources :images, :controller => "Images" do
    resources :subimages, :controller => "SubImages" do
    end
  end
end

Goal: When I make the request to user 1 it should return all of the user 1 images and sub images nested.

Right now, the code only returns the user 1 images. I want it return sub images too.

1 Answer 1

2

Use ActiveModel Serializers by Rails API. You need to create Serializer classes for your models and specifying the attributes that you require in your JSON output.

You can generate serializer for your existing models:

rails g serializer post

Given a Post and Comment model:

class PostSerializer < ActiveModel::Serializer
  attributes :title, :body

  has_many :comments

  url :post
end

and

class CommentSerializer < ActiveModel::Serializer
  attributes :name, :body

  belongs_to :post_id

  url [:post, :comment]
end

By default, when you serialize a Post, you will get its Comments as well.

Now, in your controllers, when you use render :json, Rails will now first search for a serializer for the object and use it if available.

class PostsController < ApplicationController
  def show
    @post = Post.find(params[:id])

    render json: @post
  end
end

In this case, Rails will look for a serializer named PostSerializer, and if it exists, use it to serialize the Post.

Sign up to request clarification or add additional context in comments.

2 Comments

What if I want to use the serializer conditionally? not by default.
@erielmarimon add the condition in the calling controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.