获取类别及其所有产品

时间:2013-06-27 15:45:19

标签: ruby-on-rails ruby-on-rails-3 activerecord

我有一个名为ProductCategory的模型(有许多产品)和一个模型产品(属于ProductCategory)。我在这里使用这些数据为product_categories表种子(我确定你已经猜到了,它只有两个cols(category和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)

最好的方法是什么? 我不确定这是否意味着先进或简单,对不起如果它相对容易,我还在学习。 感谢。

1 个答案:

答案 0 :(得分:1)

ProductCategories.includes(:产品)

在您看来:

<% @product_categories.each do |product_category| %>
  <%product_category.products.shuffle.take(10).each do |product| %>
    <-- display your product here -->
  <% end %>
<% end %>
相关问题