2011-08-05 27 views
2

我正在尋找一種方法來縮短生成json的respond_with內的:include =>:child。縮短response_with(:include => xxx)

下面是一個例子,不知道它是否可能,但我想知道。

在控制器:

@p = Parent.where('id = ?', params[:id]) 
respond_with(@p, :include => {:child1 => {}, :child2 => {}, :child3 => {:include => :grandchild1}}) 

有什麼方法對所有包含這些的時候,我定義的實例?

也許是這樣的:

@p = Parent.includes(:child1, :child2, :child3, :grandchild1).where('id = ?', params[:id]) 
respond_with(@p) 

基本上,我想幹涸我的代碼...我不希望有繼續鍵入遍地包括散列...有有時候只需要在一次調用中包含所有子對象?

+0

child1,的child2和child3是Parent的組合嗎?而grandchild1是child3的組合? – Thilo

+0

是的Thilo,那是對的。孩子們和孫子們會因模特而異,所以我一直在尋找一些可以像幫手一樣使用的東西......但是我正在經歷一段艱難的時光。 – ThaDick

回答

5

ActiveRecord有一個as_json方法,它定義瞭如何將對象輸出爲json。您可以ovveride此方法包括相關的兒童時默認設置是這樣的:

class Parent < ActiveRecord::Base 

    # We went to display grandchildren by default in the output JSON 
    def as_json(options={}) 
    super(options.merge(:include => {:child1 => {}, :child2 => {}, :child3 => {:include => :grandchild1}}) 
    end 


end 

這應該讓你清理你的控制器一點,你只需要這樣:

@parent = Parent.find(params[:id]) 
respond_with @parent 
+0

嗨馬里奧,我不確定重寫as_json方法在這裏會起作用。我可能會使用任何數量的關聯。所以,不知道這會起作用,除非我可以通過選項輸入各種子孫,但這與使用原始代碼相同,我錯了嗎? – ThaDick

+0

如果您打算使用不同的選項,那麼您需要將它們添加到上面的原始代碼之類的聲明中。 –

+0

你可能想要'options.reverse_merge'來達到預期的效果。 – sbeam