Rails: display unique records in each cycle
I have a product display page that displays all of the products on a website. Here I want to filter products according to their owner. First, I show the usernames on the page using each loop:
<% @products.each do |p| %>
<%= link_to p.user.profile.first_name, store_index_path %>
<% end %>
But since the owner has multiple products, his name appears multiple times. How do I show the name only once?
+3
source to share
3 answers
You can use group_by to create a User => [Products] hash. You then iterate through a unique set of users, display information about that owner, and then show each product to that user.
<% products_by_owner = @product.group_by(&:user) %>
<% products_by_owner.keys.each do |user| %>
<%= link_to p.user.profile.first_name, store_index_path %>
<% products_by_owner[user].each do |product| %>
<%= link_to product.name, store_index_path %>
<% end %>
<% end %>
+1
source to share
You can use group_by
to create a hash with users as keys and product arrays as values:
# Eager loading of users will prevent multiple database hits.
# Using find:
@products = Product.find(:all, :include => :user).group_by(&:user)
# using relations:
@products = Product.where(:some_condition => 'etc').includes(:user).group_by(&:user)
In view:
<% @products.each do |user, user_products| %>
<%= link_to p.user.profile.first_name, store_index_path %>
<% user_products.each do |product| %>
...
<% end %>
<% end %>
0
source to share