0

我有以下具有has_one关系的类,我想在我的index方法中返回它嵌套在 JSON 中。

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

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

我想respond_withindex方法上使用来返回每个数量样本以及与每个样本关联的数量对象:

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

我没有使用上面的代码获得嵌套/包含的数量对象。但是,如果我替换respond_withto_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

4

1 回答 1

1

似乎对我有用。我只是复制了提供的链接中所做的事情

respond_to :json
def index
  quantity_samples = current_user.quantity_samples.to_json(include: :quantity)
  respond_with quantity_samples
end
于 2016-01-05T14:33:36.003 回答