0

I have this each loop:

<% User.group(:team).count.each do |team, count| %>
  <%= "The '#{team}' has '#{count} User'" %>
<% end %>

The output is like this:

The 'Vikings' has '1 User' The  
'Redsocks' has '3 User' The 'Giants' has '1 User' The 
'Milan' has '2 User' The 'IKS' has '1 User' The 'Clampers' has '1 User'

I want count to be added together, and team to be added together. I want the output be something like:

the app has " 9 " users supporting "6 " different teams

Can someone advise me on how to do that?

1 Answer 1

2

This is a way to do it, but I strongly recommend you to move this count logic somewhere else than your view(s)

<% teams_count = 0 %>
<% users_count = 0 %>
<% team_users_details = [] %>
<% User.group(:team).count.each do |team, count| %>
  <% team_users_details << "The '#{team}' has '#{count} User'" %>
  <% teams_count += 1 %>
  <% users_count += count %>
<% end %>

<%= "The app has '#{users_count}' users supporting '#{teams_count}' different teams" %>
<%= team_users_details.join(' ') %>
Sign up to request clarification or add additional context in comments.

6 Comments

As for the moving of this logic elsewhere, in this case I recommend moving it to one of your models. A Team model if you have one, otherwise your User model. So you would have a method User.team_users_details that returns a hash, then the controller would call that and pass it to the view as @team_users_details, then the view would display The app has <%= @team_users_details[:users_count] %> ….
@RoryO'Kane I do not recommend to move this to the model. The model is responsible to handle the business logic, neither statistic logic nor display logic should be defined in the model. This is why you end up with fat models, skinny controllers and logic-heavy views. The decorator/presenter pattern would be great here, but if you don't want to setup this pattern, a simple Helper method should be enough.
I moved it to the controller for now, it works that way. Is it better to move it to the model or should I keep it in the controller?
I recommend you to move this in a helper. With this helper you will be able to call these methods anywhere in any of your views. If you are using the decorator/presenter pattern, use this instead of the helper.
@Slowboy also, is your app meant to be translated in other language(s) in the future? If this is an eventuality, I strongly recommend you to start using internationalization with I18n as soon as possible. It would be a real pain to have to translate a lot of hard-coded strings from all of your app's code.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.