简体   繁体   English

在索引中使用时response_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. 我有以下具有has_one关系的类,我想将其嵌套在JSON中的index方法中。

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: 我想在index方法上使用respond_with返回每个数量样本和与每个数量样本关联的数量对象:

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_withto_json

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

The :include works! :include作品!

Full JSON results: With respond_to I get: 完整的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. with to_json : 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 ? 为什么这不能与respond_with一起使用?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM