I'm struggling with a simple implementation on an array. I've read the various class methods but want to make sure I arrive at an elegant solution.
I basically want to know the raw count of how many of a certain tags there are in a given system. So if a tag belongs_to :person and a person can has_many :tags
I wonder how I might go about rendering the raw total of how many people have a "blue" tag (if there are 'blue','red', 'green' and 'orange' tags). This is the path I'm pursuing but I think the code will begin to smell soon..
<% @people.each do |person| %>
<% if person.tags.include?('blue') %>
<%= person.id %> # this is where I get stuck
<% end %>
<% end %>
So, I'm displaying the object of all the people in the system that have a blue tag, but now I need to sum those people to just get a raw count. And I need to render this a couple times in the view, one for each color (hoping to just switch out the parameter in include).
This is starting to smell because it won't become very DRY. Should this be a class method? And should I convert the returned people back to an array and call .count ?
I can eventually get the raw number but I'm a little lost here about best practice here.
---UPDATE---
This is my updated solution so far based on Gene's feedback.
Now it is much cleaner, but now I am wondering about performance because it seems slow.
I have a helper method-
def tag_count_for_person(tags_name)
@people.count {|person| person.tags.include?('tags_name') }
end
And call this method for whatever tag I need to render in the view.
<div class="well span4">
<%= tag_count_for_person("green") %>
</div>
<div class="well span4">
<%= tag_count_for_person("blue") %>
</div>
<div class="well span4">
<%= tag_count_for_person("red") %>
</div>
<div class="well span4">
<%= tag_count_for_person("hungry") %>
</div>
It still smells I believe. I shouldn't need to call this method everytime I want to render a different tag in the view? Seems costly. But then I don't have the felxibility of adding differnent tags I want to render correct? I feel like I'm much closer.