2010-08-08 57 views
3

我有三個模型(這裏簡化):如何訪問':has_many:雖然'使用to_json時連接表數據?

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調用中獲取這些數據。

任何人都可以幫助我嗎?提前謝謝了。

qryss

回答

7

不確定,但不應該這樣做嗎?

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

編輯: 這可能工作太,因爲childviews belongs_to的的overvation:

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

嘿巖, 感謝您的幫助。 這幾乎是正確的(對我來說也足夠了)。我從中得到的是一系列'needs_edit'標誌,我可以將其映射到觀察數組上。 我希望得到的是JSON哈希中的'needs_edit'標誌,用於相關的觀察。不重要;我可以與你給我的東西一起生活,所以謝謝你讓我到這裏! qryss – qryss 2010-08-09 02:17:53

+0

哦,你有一個輕微的錯字:'=>',而不是'='。 – qryss 2010-08-09 02:19:21

+0

也許你可以把:childviews => {:only =>:needs_edit}放在:obervations hash裏面? (見編輯)對於給定的觀察結果,這應該包括needs_edit值,但我不確定。 – Rock 2010-08-09 02:50:00

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

謝謝,搖滾!這是做我的頭。

:)

qryss