我有这个each
循环:
<% User.group(:team).count.each do |team, count| %>
<%= "The '#{team}' has '#{count} User'" %>
<% end %>
输出如下:
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'
我希望将count
添加到一起,并将team
添加到一起。我希望输出类似于:
the app has " 9 " users supporting "6 " different teams
有人可以告诉我如何做到这一点吗?
答案 0 :(得分:2)
这是一种方法,但我强烈建议您将此计数逻辑移到除视图之外的其他地方
<% 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(' ') %>