在索引中使用时,respond_with不包含嵌套资源

时间:2016-01-04 08:01:45

标签: ruby-on-rails json respond-with

我有以下具有has_one关系的类,我希望在我的index方法中将其嵌套在JSON中。

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

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

我想在索引方法上使用respond_with来返回每个数量样本和与每个样本相关联的数量对象:

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

我没有使用上面的代码获得嵌套/包含的数量对象。但是,如果我将respond_with替换为to_json

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

:include有效!

完整的JSON结果:respond_to我得到:

{"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。与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}}]

为什么这不适用于respond_with

1 个答案:

答案 0 :(得分:1)

似乎适合我。我刚刚复制了link提供的内容

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