2014-09-12 37 views
0

對於我的API,我需要加載所有客戶端,客戶端項目及其價格並將它們返回爲JSON或XML。Rails 3渴望加載幷包含json或xml中的關聯屬性

Model Client 
has_many items 

Model Item 
belongs to :client 
has_many :prices 

Model Price 
belongs_to :item 

我需要建立可以使用來自所有三個協會與每一個客戶盯着所有屬性的分級結果@tree - >每個項目 - >每個價格發回的JSON和API調用的XML響應。

這樣:

@tree = Client_1 
     --Item_1 
      --Price_1 
      --Price_2 
     --Item_2 
      --Price_3 
      --Price_4 
     Client_2 
     ... and so on 
 respond_to do |format| 
     format.xml {render :xml =>{@tree}} 
     format.json {render :json =>{@tree}} 
     end 

更新::

我曾嘗試包括,連接,預加載eager_load和一切。所有這些只會帶來最頂級模型即客戶端的屬性。他們不加載來自關聯的屬性。我甚至試過Retrieve all association's attributes of an AR model?。它有點做我需要但不是全部。它不會將@tree放在我需要的層次結構中。它創建它像

@tree = Client_1 
     --Item_1 
     --Item_2 
     --Price_1 
     --Price_2 
     --Price_3 
     --Price_4 

這不是我所需要的。

+0

你嘗試過什麼。你有沒有看過'eager_load'或'include'作爲查詢方法?甚至可以在模型中建立這種模式,所以如果這是你的意圖,但是不知道你已經自己嘗試過了,那麼這些模塊總是被急切加載,我寧願不只是爲你解決問題。 – engineersmnky 2014-09-12 19:30:22

回答