Search code examples
ruby-on-railsapiruby-on-rails-5active-model-serializersactivemodel

how to define association in ActiveModel::Serializer


I have following Serializer

class BookSerializer < ActiveModel::Serializer
  attributes :id, :name, :publisher, :author, :cover_url
  has_many :chapters
end

I have two method in bookscontroller.rb file as follows:

def index
  books = Book.select(:id, :name, :publisher, :publisher, :cover, :author)
  if books.present?
    render json: books
  end
end

def show
  book = Book.find_by_id params[:id]
  render json: book
end

Actually everything is working fine but the problem is I want chapters records in show page not on index page, but right now query for fetching chapters are running in both action but I only want to include has_many :chapters in show action.

So Is there any way that can I use association for particular method in rails controller?


Solution

  • You can use different serializers for different actions. For example, remove has_many :chapters from BookSerializer and create a separate BookWithChaptersSerializer. Use it as follows:

    class BookWithChaptersSerializer < ActiveModel::Serializer
      attributes :id, :name, :publisher, :author, :cover_url
      has_many :chapters
    end
    
    def show
      book = Book.find_by_id params[:id]
      render json: book, serializer: BookWithChaptersSerializer
    end