Search code examples
ruby-on-railsruby-on-rails-4active-model-serializers

How to fetch all objects of a model in serializer?


I'm using ActiveModelSerializer for a Rails API. On some controller inside index action I need to display all existing objects of class Book.

def index
  render json: { books: Book.all }
end

But I suppose this isn't the right way. To follow convention, I need to use serializer. So my question is how could I achieve this using serializer, so I could write something like this?

def index
  render json: { books: BookSerializer }
end

Thank you.


Solution

  • This should work

    def index
      books = Book.all
      render json: books, each_serializer: BookSerializer, root: books
    end
    

    P.S. Beware though rendering all books will be slow. It's better to add pagination