Komb
(Komb')
September 7, 2006, 4:19pm
1
I can't quite figure out how to set up the inject command to do what I
want. (or if it's even possible)
What I'm trying to do:
Create a list of categories from a search of the items table. Count how
many of each category appeared, and output that to the view.
This is the code I have so far:
@categories = @items.collect {|item| ["name"=>item.category.name,
?> "id"=>item.category.id]}
=> [[{"name"=>"Cat 1", "id"=>1}], [{"name"=>"Cat 2", "id"=>2}],
[{"name"=>"Cat 2", "id"=>2}], [{"name"=>"Cat 3", "id"=>3}]]
I'm trying to use a modified version of this > list.inject(Hash.new(0))
{ |h, x| h += 1; h}< to create a @categories containing "name", "id"
and "count".
This is a sample of many things I have tried. (I clearly don't
understand how this command works)
@categories.inject (Hash.new(0)) {|cat| ["name"=>cat.name, "id"=>cat.id,
"count"=>cat.count += 1]}
Any help appreciated.
Lance
Komb
(Komb')
September 7, 2006, 5:55pm
2
At this point, I'm guessing that the collect statment isn't getting the
data in a useful format.....
Any Ideas?
Chris_Hall
(Chris Hall)
September 7, 2006, 6:02pm
3
try
@category_counts = Hash.new(0)
@items.collect { |item| item.category }.each { |cat|
@category_counts [cat.name] += 1 }
this will give you something like
{"cat1" => 3, "cat2" => 5, "cat3" => 10}
in @category_counts
Komb
(Komb')
September 7, 2006, 6:35pm
4
Thanks for the input.
Tried using that, and my
@categories = @items.collect {|item| ["name"=>item.category.name,
"id"=>item.category.id]}
Code with this view code:
<% if @categories -%>
<% @categories.each do |cat| %>
<p><a href="search?cat=<%= cat.id %>" class="leftnav"> <%=
cat.name %></a>
<% if @category_counts -%>
<%= @category_counts [cat.name]%>
<% end -%>
</p>
<% end %>
<% end -%>
And as I suspected my @categories if not properly formated...
I have sofar been unable to format it anyother way...
Komb
(Komb')
September 7, 2006, 8:25pm
5
Thank you for a very clear explination of how inject works.
I'm sure it will be of help, after I figure out how to fix my collect
problem.