2013-06-27 112 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

相关问题