如何在rails中使用.each方法时将两列放置在一行中



我想在使用'.each'方法时,在表数据标记中每行显示两列代码。但问题是以下代码在一行中显示一列。

<table>
<% @lease.apartment.roommates.each do |roommate| %>
<tr>
<td colspan="5">
<% unless roommate == @lease.second_occupant || roommate == @lease.user %>        
<% if roommate.current_room.present? %>
<p>
<%= roommate.full_name %> - 
<% if roommate.current_room.apartment == @lease.apartment%>
<%= roommate.current_room&.label %> 
<% end %>
<br>Email:<%= roommate.email %><br>Phone:<%= roommate.phone %><br>
<% if @lease.end_at.present? %>
Lease End date (if applicable):<%= @lease.end_at %>
<% end %>
</p>
<% end %>
<% end %>
</td>
</tr>
<% end %>
</table>

您可以这样做,以便在一行中获得两列

<table>
<% @lease.apartment.roommates.each_with_index do |roommate, i| %>
<% if (i+1)%2 == 1%>
<tr>
<% end %>
<td colspan="5">
<% unless roommate == @lease.second_occupant || roommate == @lease.user %>        
<% if roommate.current_room.present? %>
<p>
<%= roommate.full_name %> - 
<% if roommate.current_room.apartment == @lease.apartment%>
<%= roommate.current_room&.label %> 
<% end %>
<br>Email:<%= roommate.email %><br>Phone:<%= roommate.phone %><br>
<% if @lease.end_at.present? %>
Lease End date (if applicable):<%= @lease.end_at %>
<% end %>
</p>
<% end %>
<% end %>
</td>
<% if (i+1)%2 == 0%>
</tr>
<% end %>
<% end %>

嗨,您可以使用tadman 评论中提到的each_slice

<table>
<% @lease.apartment.roommates.each_slice(2) do |roommate_pair| %>
<% roommate_pair.each do |roommate| %>

<tr>
<td colspan="5">
<% unless roommate == @lease.second_occupant || roommate == @lease.user %>        
<% if roommate.current_room.present? %>
<p>
<%= roommate.full_name %> - 
<% if roommate.current_room.apartment == @lease.apartment%>
<%= roommate.current_room&.label %> 
<% end %>
<br>Email:<%= roommate.email %>
<br>Phone:<%= roommate.phone %><be>
<% if @lease.end_at.present? %>
Lease End date (if applicable):<%= @lease.end_at %>
<% end %>
</p>
<% end %>
<% end %>
</td>
</tr>
<% end %>
<% end %>
</table>

我希望这对你有帮助。

最新更新