简体   繁体   中英

How to range users in 3 columns in every line, instead of on 1 column?

How to range users on 3 columns in every line, instead of on 1?

Instead this:

User             
User
User
User
User
User

I need:

User User User
User User User

view.rb

 <%= content_tag_for :td, @users do |s| %><div id="f">
<td><pre> <%= image_tag(s.image, height: '45', width: '32') %> <%= link_to s.display_name, users_path(s.id)%></pre></td>
<br>                               
</div>
<% end %>

controller.rb

def p
    @users = User.search(params[:search])
  end

.in_groups_of(x) is what you are looking for:

<table>
  <% @users.in_groups_of(3) do |users| %>
    <tr>
      <% users.each do |user| %>
        <td><%= user.try(:display_name) %></td>
      <% end %>
    </tr>
  <% end %>
</table>

I used user.try(:display_name) because if @users % 3 != 0 , you will end up with the last array filled with nil s.

Example:

User.limit(5).in_groups_of(3)
# returns
[
  [<User id:...>, <User id:...>, <User id:...>],
  [<User id:...>, <User id:...>, nil]
]

in_groups is your friend

<% @users.in_groups(3, false) do |users| %>
  <tr>
    <% users.each do |user| %>
      <td class="user"><%= user.name %></td>
    <% end %>
  </tr>
<% end %>

Use Array#in_groups :

<tr>
  <% @users.in_groups(3).each do |groups_of_users| %>
    <td>
      <% groups_of_users.reject{ |u| u.nil? }.each do |user| %>
        <div><%= user.name %></div>
      <% end %>
    </td>
  <% end %>
</tr>

Oh, and switch to Haml . :) That turns this into:

%tr
  - @users.in_groups(3).each do |groups_of_users|
    %td
      - groups_of_users.reject{ |u| u.nil? }.each do |user|
        %div= user.name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM