开发者

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=>'开发者_JAVA百科role asc')

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


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 %>


 <% 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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜