2013-04-24 34 views
1

我有這樣的index.rabl:Rails的Rabl的顯示集合在此對象的對象和兒童

collection @exchangers, :root => "bank", :object_root => false 

extends "exchanger_lists/show" 

和這樣show.rabl:

object @exchanger 
attributes :id, :name, :address, :location_id, :latitude, :longitude, :exchanger_type_id 
node(:location_name) {|exchanger_list| exchanger_list.location.name } 
node(:exchanger_type_name) {"normal" } 
child @currencies do 
     attribute :value, :direction_of_exchange_id, :exchanger_list_id 
end 

我位指示是這樣的:

def index 
    @exchangers = ExchangerList.all 
    end 
def show 
    @exchanger = ExchangerList.find(params[:id]) 
    @currency_list = CurrencyList.all 
    @currencies = [] 
    @currency_list.each do |c| 
     @currencies << CurrencyValue.find(:all, :conditions => {:currency_list_id => c.id, :exchanger_list_id => @exchanger.id}, :order => :updated_at).last(2) 
    end 
    @currencies.flatten! 
    end 

如果我打電話瀏覽器顯示方法,我看到孩子@currencies和它的數據,但如果我打電話索引我看到所有(我也看到節點),但孩子,我沒有e ....怎麼了?我做得不好?

+0

你的意思是你看不到@currencies子節點?當您調用index並僅渲染顯示模板時,此實例變量將爲零。 – dan 2013-04-24 12:19:08

+0

@dan是的,也許你是對的....但如何才能解決我的問題? – 2013-04-24 12:23:20

+0

我不會理睬你,我發佈了一個答案,因爲評論中缺少空間。 – dan 2013-04-24 12:47:27

回答

1

你的架構有點搞砸了,因爲在show動作中你不僅顯示一個@exchanger,而且當你在索引模板中渲染顯示時,@currencies的完整列表爲零。總的來說,我會建議你考慮整個應用程序架構。

當我應該給你一個簡單的解決方案爲你當前的問題,我會從show動作提取@currencies代碼到app/helpers/currency_helper.rb中的助手方法,並從展示模板中訪問它。

module CurrenciesHelper 

    def currencies(exchanger) 
    currencies = CurrencyList.all.map do |c| 
     CurrencyValue.find(:all, :conditions => {:currency_list_id => c.id, :exchanger_list_id => exchanger.id}, :order => :updated_at).last(2) 
    end 
    currencies.flatten! 
    end 

end 

順便說我map取代each方法,因爲它適合在這種情況下更好。

更改貨幣部分顯示模板

child currencies(@exchanger) do 
    attribute :value, :direction_of_exchange_id, :exchanger_list_id 
end 
+0

好的,請嘗試,請添加關於要寫什麼然後在視圖和方法 – 2013-04-24 12:49:59

+0

信息我更新了我的答案 – dan 2013-04-24 12:54:37

+0

在show動作一切正常,但在我看來我被稱爲id爲零,這將錯誤地爲4也許因爲並非所有在數據庫中的數據是鏈接的,並非所有的交換器都有currency_values ....是真的趕上它並解決? – 2013-04-24 12:57:02