我有以下具有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
?
答案 0 :(得分:1)
似乎适合我。我刚刚复制了link提供的内容
respond_to :json
def index
quantity_samples = current_user.quantity_samples.to_json(include: :quantity)
respond_with quantity_samples
end