2013-06-27 117 views
0

我有一個名爲ProductCategory(有許多產品)和一個模型產品(屬於ProductCategory)的模型。我播種product_categories表這個數據在這裏(我相信你已經猜到了,它只有兩個的cols(類別和category_type)。獲取類別及其所有產品

product_categories = [ 
    {:category => "Arts", :category_type => "physical" }, 
    {:category => "Books", :category_type => "physical" }, 
    {:category => "Comics", :category_type => "digital" }, 
    {:category => "Diy & Craft", :category_type => "physical" }, 
    {:category => "E-books", :category_type => "digital" } 
] 

現在在我的產品指標我要顯示所有類別隨着10個隨機產品在每個類別。後來我會改變到前十。
我最終希望實現的一個例子是This http://s866.photobucket.com/user/tommyadey/media/products.jpg.html
但在我的情況下,我想顯示所有的類別和看到每個類別的十種產品 我試過了:

ProductCategory.includes(:products).limit(10) 

什麼是最好的方式去做這件事? 我不確定這是否意味着先進或簡單,對不起,如果它相對容易,我還在學習。 謝謝。

+0

你的意思是屬於產品類別權10級隨機的產品呢? – usha

+0

嗯,這是正確的:) – Skyalchemist

回答

1

ProductCategories.includes(:產品)

在你看來:

<% @product_categories.each do |product_category| %> 
    <%product_category.products.shuffle.take(10).each do |product| %> 
    <-- display your product here --> 
    <% end %> 
<% end %> 
+0

非常感謝Vimsha,我會去嘗試一下。 – Skyalchemist

+0

它表示列products.product_category_id不存在,但我的產品表中有category_id。 – Skyalchemist

+0

當您聲明您的關聯時,請明確指定foreign_key。 'belongs_to:product_category,:foreign_key =>「product_id」' – usha

相關問題