I am trying to make a list of categories returned by a search of the items table. Including # of times that category showed up in the list. The items and categories tables are linked like the recipe tutorial. That is: <% @items.each do |item| -%> <%= items.category.name %> <% end -%> will list all the category names. I''ve found code that will enumerate how many times something shows up in an array, But have no idea how to apply it to the list of items. Here''s the link to the code: (Doh lost link is browser crash) This is the heart of the code from another site: inject(Hash.new(0)) {|hash, element| hash[element] += 1; hash} Unfortunatly, I have no idea how to get the list of categories from the @items and feed them to/through this code to get the result I want. (Or even something I can work with) What I would idealy like to end up with is a @categories containing name, id and count so I could use code like: <% @categories.each do |cat| %> <p><a href="search?cat=<%= cat.id %>" class="leftnav"> <%cat.name%></a> <% if cat.count -%> <%= cat.count %> <% end -%> </p> <% end -%> in the view. Thanks Lance F. Squire --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk -~----------~----~----~----~------~----~------~--~---
After trying to figure out how ''inject'' worked, I stumbled on ''collect'' I can now get a list of categories from the items like so: list = @items.collect{|item| item.category.id} returns [1, 2, 2, 3] And I can get a count with the previous code like this: @count = list.inject(Hash.new(0)) { |h, x| h[x] += 1; h} returns {1=>1, 2=>2, 3=>1} I still haven''t figured out how to incorporate this into the @categories though... --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk -~----------~----~----~----~------~----~------~--~---