Skyalchemist
Skyalchemist

Reputation: 461

Getting categories and all its products

I have a model called ProductCategory(has many products) and a model Products(belongs to ProductCategory). I seed the product_categories table with this data here(I'm sure you've guessed it, it has only two cols (category and 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" }
]

Now in my product index i want to display all the categories along with 10 random products in each of the categories. Later i will change that to the top ten.
An example of what i'm ultimately hoping to achieve is This http://s866.photobucket.com/user/tommyadey/media/products.jpg.html
But in my case i want to display all the categories and see ten products from each categories. I've tried:

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

What would be the best way to go about this? I'm not sure if this is meant to be advanced or simple, sorry if it's relatively easy, i'm still learning. Thanks.

Upvotes: 0

Views: 116

Answers (1)

usha
usha

Reputation: 29369

ProductCategories.includes(:products)

In your view:

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

Upvotes: 1

Related Questions