[英]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_with
与to_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
一起使用?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.