3

私は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 結合テーブルにあるデータも取得したいと考えています。特に「needs_edit」の値。

to_json 呼び出しでこのデータを取得する方法がわかりません。

誰でも私を助けることができますか?よろしくお願いします。

クリス

4

2 に答える 2

7

よくわかりませんが、これでうまくいきませんか?

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

編集:子ビューがオーバーベーションに属しているため、これも機能する可能性があります:

@child.to_json(
  :include => {
    :observations => {
      :include => { :photos, :childviews => { :only => :needs_edit } } 
      :methods => [:key, :title, :subtitle]
    }
  }, 
  :except => [:password]
)
于 2010-08-08T23:33:23.433 に答える
2

ポインタをくれたロックに感謝します-私は今それを機能させています!

このコード:

@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
                    }
                ]
            }
        ]
    }
}

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

:)

クリス

于 2010-08-09T07:06:39.813 に答える