Rober
Rober

Reputation: 6108

Rails 4 render json with multiple objects and includes

I have a Rails 4 API. When a user search in the view for boats, this method is executed getting all the boats matching the search filters and return an array of boat models as json using render ActiveModel and the :include and :only like this:

render :json => @boats, :include => { :mainPhoto => {:only => [:name, :mime]},
                                      :year => {:only => :name},
                                      # other includes...}

This is working great.

But, additional to this information, in the view, I would like to show the total count of boats like "showing 1 - 20 of 80 boats" because there is a pagination funcionality. So, the point is I need to provide the 80 boats. I would like to avoid send two requests that execute almost the same logic, so the idea is to run the searchBoats method just once and in the result provide the list of boats and the total number of boats in a variable numTotalBoats. I understand numTotalBoats is not a boat model attribute. So, I think it should go in an independent variable in the render result. Something like:

render :json => {boats: @boats with all the includes, numTotalBoats: @NumTotalBoats}

I tried thousands of combinations, but or I´m getting syntax errors or none of them is returning the expected result, something like

{boats: [boat1 with all the includes, boat2 with all the includes, ... boatN with all the includes], numTotalBoats: N}

Upvotes: 1

Views: 2575

Answers (1)

Marcin Kołodziej
Marcin Kołodziej

Reputation: 5313

Without adding any gems:

def index
  boats = Boat.includes(:year)

  render json: {
    boats: boats.as_json(include: { year: { only: :name } }),
    numTotalBoats: boats.count
  }
end

At some point though, I believe you should use stand-alone serializers:

Note: Depending on whether you're using pagination gem or not, you might need to change .count calls below to .total_count (for Kaminari) or something else that will read the count correctly from paginated collection.

I recommend using ActiveModel Serializers and this is how it would be accomplished for your case.

Start by adding the gem to Gemfile:

gem 'active_model_serializers', '~-> 0.10'

Overwrite the adapter in config/initializers/active_model_serializer.rb:

ActiveModelSerializers.config.adapter = :json

Define serializers for your models,

# app/serializers/boat_serializer.rb
class BoatSerializer < ActiveModel::Serializer
  attributes :name

  has_one :year
end

# app/serializers/year_serializer.rb
class YearSerializer < ActiveModel::Serializer
  attributes :name
end

And finally, in your controller:

boats = Boat.includes(:year)

render json: boats, meta: boats.count, meta_key: "numTotalBoats"

And you will achieve:

{
  "boats": [
    {
      "name": "Boaty McBoatFace",
      "year": {
        "name": "2018"
      }
    },
    {
      "name": "Titanic",
      "year": {
        "name": "1911"
      }
    }
  ],
  "numTotalBoats": 2
}

Adding that count in each index controller is a bit tedious, so I usually end up defining my own adapters or collection serializers in order to take care of that automatically (Tested with Rails 5, not 4).

# lib/active_model_serializers/adapter/json_extended.rb
module ActiveModelSerializers
  module Adapter
    class JsonExtended < Json
      def meta
        if serializer.object.is_a?(ActiveRecord::Relation)
          { total_count: serializer.object.count }
        end.to_h.merge(instance_options.fetch(:meta, {})).presence
      end
    end
  end
end

# config/initializers/active_model_serializer.rb
ActiveModelSerializers.config.adapter = ActiveModelSerializers::Adapter::JsonExtended

# make sure to add lib to eager load paths
# config/application.rb
config.eager_load_paths << Rails.root.join("lib")

And now your index action can look like this

def index
  boats = Boat.includes(:year)

  render json: boats
end

And output:

{
  "boats": [
    {
      "name": "Boaty McBoatFace",
      "year": {
        "name": "2018"
      }
    },
    {
      "name": "Titanic",
      "year": {
        "name": "1911"
      }
    }
  ],
  "meta": {
    "total_count": 2
  }
}

I think it's a little easier to parse this count for different endpoints and you will get it automatically while responding with a collection, so your controllers will be a little simpler.

Upvotes: 4

Related Questions