我有以下具有has_one
关系的类,我想在我的index
方法中返回它嵌套在 JSON 中。
class QuantitySample < ActiveRecord::Base
has_one :quantity, :dependent => :destroy
...
class Quantity < ActiveRecord::Base
belongs_to :quantity_sample
...
我想respond_with
在index方法上使用来返回每个数量样本以及与每个样本关联的数量对象:
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}]}
与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
?