簡體   English   中英

在索引中使用時response_with不包含嵌套資源

[英]respond_with when used in index does not include nested resources

我有以下具有has_one關系的類,我想將其嵌套在JSON中的index方法中。

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

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

我想在index方法上使用respond_with返回每個數量樣本和與每個數量樣本關聯的數量對象:

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一起使用?

似乎為我工作。 我只是復制了所提供鏈接中的內容

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