ruby-on-railsrubyapiruby-grapepresenter

presenting resources in API


im preparing Rails 5 API and i have some GET endpoints which do nothing but presenting resources to enduser.

how can i limit what the user can see. Lets say i have a table Books, with title and author columns, i want the enduser to get his book with a title and an author but i dont want to give him stuff like :id or timestamps. is there an existing solution similar to what grape has to offer with present() and Grape::Entity classes?


Solution

  • The cleanest way to do this would be with a serializer.

    # app/serializers/book_serializer.rb
    class BookSerializer < ActiveModel::Serializer
      attributes :title, :author
    end
    

    Then in the controller:

    def show
      book = Book.find(params[:id])
      render json: book, serializer: BookSerializer
    end