John
John

Reputation: 6612

Output in row or column based on value

I want to show all my users grouped in rows based on their role. So one row with all admin users, one row with all premium users, etc. In my view I have this:

   <% @users.each do |user| %>
    <tr>
      <td><%=h user.name %></td>
      <td><%=h user.role %></td>
    </tr>
   <% end %>

And in the controller I have this:

@users = User.find(:all, :order=>'role asc')

This will nicely output all users, but every users on a separate row. Any ideas? Thanks!

Upvotes: 0

Views: 198

Answers (2)

John
John

Reputation: 6612

 <% users.each do |user| %>
  <span><%= user.name %></span>
<% end %>

Is there a way I can count the number of user names in this each loop?

Upvotes: 0

DanneManne
DanneManne

Reputation: 21180

After you have retrieved all users from the db, you can group them into a hash by their role and then loop through that result, perhaps like this:

@users = User.all(:order => "role ASC").group_by(&:role)

This will result in a hash:

=> {"admin" => [<User...>, <User...>, ...], "premium" => [<User...>]}

So in your views you could loop through them with the each_pair method:

<% @users.each_pair do |role, users| %>
  <tr>
    <td><%= role %><td>
    <td>
    <% users.each do |user| %>
      <span><%= user.name %></span>
    <% end %>
    </td>
  </tr>
<% end %>

Upvotes: 1

Related Questions