どのようにアクセスするto_jsonをを使用している場合、テーブルのデータを結合「:has_manyの通じ」?

StackOverflow https://stackoverflow.com/questions/3433631

質問

I(ここでは単純化)3つのモデルがあります:

class Child < ActiveRecord::Base
  has_many    :childviews, :dependent => :nullify
  has_many    :observations, :through => :childviews  
end
class Childview < ActiveRecord::Base
  belongs_to  :observation
  belongs_to  :child
end
class Observation < ActiveRecord::Base
  has_many    :childviews, :dependent => :nullify
  has_many    :children, :through => :childviews
end

私はこのようなRailsのto_jsonをメソッドを使用して、いくつかのJavaScriptにこれを送信しています

render :layout => false , :json => @child.to_json(
  :include => {
    :observations => {
      :include => :photos, 
      :methods => [:key, :title, :subtitle]
    }
  },
  :except => [:password]
)

これは完璧に動作します。観察は、テーブルを結合「を介して」罰金を取得している(childviews)。

がしかしの、私もchildviewsに座って、テーブルを結合するデータを取得したいです。特に 'needs_edit' の値ます。

私はto_jsonを呼び出しで、このデータを取得する方法を見つけ出すことはできません。

缶誰の助け私?事前に感謝します。

qryss

役に立ちましたか?

解決

わからないものでなければならない、この作品?

@child.to_json(
  :include => {
    :observations => {
      :include => :photos, 
      :methods => [:key, :title, :subtitle]
    },
    :childviews => { :only => :needs_edit }
  }, 
  :except => [:password]
)

編集: これはovervation belongs_toのchildviewsいるので、あまりにも動作します。

@child.to_json(
  :include => {
    :observations => {
      :include => { :photos, :childviews => { :only => :needs_edit } } 
      :methods => [:key, :title, :subtitle]
    }
  }, 
  :except => [:password]
)

他のヒント

ポインタのためのロックのおかげ! - 私は今、それが働いています。

このコード:

@child.to_json(:include => 
  {
    :observations => {
      :include => {
        :photos => {},
        :childviews => {:only => :needs_edit}
      }, 
      :methods => [:S3_key, :title, :subtitle]
    }     
  },
  :except => [:password]
)

は私に(明確にするため省略)、この出力を提供します

{
    "child":
    {
        "foo":"bar",
        "observations":
        [
            {
                "foo2":"bar2",
                "photos":
                [
                    {
                        "foo3":"bar3",
                    }
                ],
                "childviews":
                [
                    {
                        "needs_edit":true
                    }
                ]
            }
        ]
    }
}

、ロックをありがとう!それはで私の頭をしていた。

:)

qryss

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top