val_to_many
val_to_many

Reputation: 377

:limit number of rows found in a collect (has_many association)

Category

has_many :products
has_many :deals, :through => :products

Product

has_many :deals

I want to display a limited number of deals on a category page.

In categories_helper.rb:

def deals
 @category.products.collect { |c| c.deals}.flatten
end

In the show.html.erb (Category):

<% for deal in deals  %>
 <%=  deal.name %>
<% end %>

This works fine, BUT it obviously throws out all deals for the products in that category and I want only 8 of them. So I would like to apply a (:limit => 8) to the .collect. I just can't figure out where it would go. Also I would like to do a second find with an (:offset => 8) which I'll show only on request.

Upvotes: 1

Views: 1126

Answers (2)

Ju Nogueira
Ju Nogueira

Reputation: 8461

You don't need the collect since you have the has-many-through association. I believe this is what you're looking for:

@category.deals.all(:limit => 8)

Upvotes: 2

Can Berk G&#252;der
Can Berk G&#252;der

Reputation: 113280

This should work:

@category.products.find(:all, :limit => 8)

Upvotes: 1

Related Questions