Search code examples
ruby-on-railsjsonrespond-with

respond_with when used in index does not include nested resources


I have the following classes with a has_one relationship and I want to return it nested in JSON in my index method.

class QuantitySample < ActiveRecord::Base
  has_one :quantity, :dependent => :destroy
  ...

class Quantity < ActiveRecord::Base
  belongs_to :quantity_sample
  ...

I want to use respond_with on the index method to return each of the quantity samples and the quantity object associated with each one:

class QuantitySamplesController < ApplicationController
  respond_to :json
  def index
    quantity_samples = current_user.quantity_samples
    respond_with quantity_samples, :include => {:quantity => {}}
  end
  ...

I don't get the nested / included quantity objects with the above code. However, if I replace respond_with with to_json:

respond_to do |format|
  format.json do
    render :json => quantity_samples.to_json(:include => {:quantity => {}})
  end
end

The :include works!

Full JSON results: With respond_to I get:

{"quantity_samples"=>[{"id"=>1, "start_date"=>"2016-01-04T07:38:40.694Z", "end_date"=>"2016-01-04T07:38:40.694Z", "user_id"=>1, "workout_id"=>nil, "created_at"=>"2016-01-04T07:38:41.328Z", "updated_at"=>"2016-01-04T07:38:41.328Z", "quantity_type"=>"HKQuantityTypeIdentifierDistanceWalkingRunning", "device"=>nil, "metadata"=>nil}]}

vs. with to_json:

[{"id"=>1, "start_date"=>"2016-01-04T07:36:09.415Z", "end_date"=>"2016-01-04T07:36:09.415Z", "user_id"=>1, "workout_id"=>nil, "created_at"=>"2016-01-04T07:36:10.110Z", "updated_at"=>"2016-01-04T07:36:10.110Z", "quantity_type"=>"HKQuantityTypeIdentifierDistanceWalkingRunning", "device"=>nil, "metadata"=>nil, "quantity"=>{"id"=>2, "value"=>4200.0, "unit"=>"m", "created_at"=>"2016-01-04T07:36:10.123Z", "updated_at"=>"2016-01-04T07:36:10.123Z", "name"=>nil, "quantity_sample_id"=>1}}]

Why isn't this working with respond_with?


Solution

  • Seems to work for me. I just replicated what was done in the link supplied

    respond_to :json
    def index
      quantity_samples = current_user.quantity_samples.to_json(include: :quantity)
      respond_with quantity_samples
    end