2013-02-04 47 views
1

我在這裏可能忽略了一個簡單的方法,但是編寫一個2軸動態表格的最佳方法是什麼?我使用Rails 3.2如何在Rails中設置雙向動態表格

例如,說我有以下型號

class Region 
    has_many :shops 
end 

class Shop 
    has_many :sales 
    has_many :products, through: :sales 
end 

class Sale 
    belongs_to :shop 
    belongs_to :product 
end 

class Product 
    has_many :sales 
    has_many :shops, through: :sales 
end 

在地區放映視圖我要顯示一個表格,在列標題列出了商店,產品爲行標題,並計算每個單元的平均Sale.price

我正在陷入混亂的嵌套塊混亂,計算值似乎不符合我的預期。

有沒有一個簡單的Rails-y方法來做這樣的事情?或者任何人都可以推薦我可以學習的任何示例代碼

我的實際模型比我描述的要複雜得多,我想知道我是否應該花時間在代碼中進行調試,或者我是否應該遵循更簡單的方法。這似乎是一個相當普遍的要求。

編輯

我的代碼

#views/regions/show.html.erb 
<table> 
    <tr> 
    <th>Shop Name</th> 
    <% for product in @region.products.uniq %> 
     <th><%= product.name%></th> 
    <% end %> 
    </tr> 
    <% for shop in @region.shops.uniq %> 
    <tr> 
     <td><%= shop.name %></td> 
     <% for product in @region.products.uniq %> 
     <td><%= product.sales.average(:price, conditions: ['sale.shop_id = ?', shop], :include => :sale) %></td> 
     <% end %> 
    </tr> 
    <% end %> 
</table> 

回答

1

一個例子你可以試試這個計算每個店鋪的平均銷售。

Shop.joins(:sales).average(:price, group: :product_id)

這將導致與散列,其中鍵是產品ID和值是平均爲產物。如果你想展示的不僅僅是產品編號的詳細信息,您可以:group選項更改爲類似(使用postgre)

Shop.joins(sales: :product).average(:price, group: "product_id || ' - ' || products.name")

UPDATE:使用上的問題的視圖模板(警告,這將是在一個大組記錄)減緩

#views/regions/show.html.erb 
<table> 
    <tr> 
    <th>Shop Name</th> 
    <% @region.products.each do |product| %> 
     <th><%= product.name%></th> 
    <% end %> 
    </tr> 
    <% @region.shops.each do |shop| %> 
    <tr> 
     <td><%= shop.name %></td> 
     <% shop.products.each do |product| %> 
     <td><%= product.sales.where(shop_id: shop.id).average(:price) %></td> 
     <% end %> 
    </tr> 
    <% end %> 
</table> 

UPDATE:這可能是做

# controller 
@shops = @region.shops 
@products = Product.joins(:shops).where(shops: { region_id: @region.id }) 
@averages = Sale.joins(:shop).average(:price, group: ['shops.id', 'shops.name', 'sales.product_id]) 

# view 
<tr> 
    <th>Shop Name</th> 
    <% @products.each do |product| %> 
    <th><%= product.name%></th> 
    <% end %> 
</tr> 
<% @shops.each do |shop| %> 
    <tr> 
    <td><%= shop.name %></td> 
    <% @products.each do |product| %> 
     <td><%= @averages[[shop.id, shop.name, product.id]] || 0 %></td> 
    <% end %> 
    </tr> 
<% end %> 
+0

嗨jvnil一個更快的方式,感謝這個有用線。儘管如此,我仍然在努力研究如何在表格中構建計算(我預計我會很慢)。我用我的代碼更新了我的問題。它不是按原樣工作,即使是這種方法的表現也不理想。感謝任何指導,幫助我想象這是如何工作的。 –

+0

嘿@AndyHarvey,我已經更新了我的答案。如果你只需要顯示文本,你可以使用我的第一個答案,這樣你就不會創建更快的活動記錄對象。如果您需要訪問商店和產品,請使用第二個。 – jvnill

+0

太棒了,我知道我的密碼正在查詢中!同意你的表現可能受損。有沒有更好的方法來做到這一點,使數據庫交互最小化?或者這是否和它一樣好? –