: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.
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)
This should work:
@category.products.find(:all, :limit => 8)
精彩评论