Sql 在rails中的列上循环
这可能很容易,但我很难弄明白 我有一部分:Sql 在rails中的列上循环,sql,ruby-on-rails,ruby,loops,partial,Sql,Ruby On Rails,Ruby,Loops,Partial,这可能很容易,但我很难弄明白 我有一部分: <% for room in @scrape %> <tr id="page_<%= room.id %>"> <th scope="row" class="<%= cycle("spec", "specalt") -%>"><%=h room.name %></td> <td class="<%=current_cycle%>">
<% for room in @scrape %>
<tr id="page_<%= room.id %>">
<th scope="row" class="<%= cycle("spec", "specalt") -%>"><%=h room.name %></td>
<td class="<%=current_cycle%>"><%=h room.day1 %></td>
<td class="<%=current_cycle%>"><%=h room.day2 %></td>
<td class="<%=current_cycle%>"><%=h room.day3 %></td>
<td class="<%=current_cycle%>"><%=h room.day4 %></td>
<td class="<%=current_cycle%>"><%=h room.day5 %></td>
<td class="<%=current_cycle%>"><%=h room.day6 %></td>
<td class="<%=current_cycle%>"><%=h room.day7 %></td>
<td class="<%=current_cycle%>"><%= select_tag("room[#{room.id}]", options_for_select(0..room.spots,0)) %></td>
</tr>
<% end %>
但我不知道会有多少天,我如何循环浏览不同天的列结果?这可以在助手中使用block/yield完成,但这超出了您的问题范围。我将通过在部分中执行此操作直接进入问题
<% room.attributes.each do |key, value| %>
<% if key.to_s.include?("day") %>
<td class="<%=current_cycle%>"><%=h value.to_s %></td>
<% end %>
<% end %>
现在这是你的部分:
<% attributes_for(room, "day") do |key, value| %>
<td class="<%=current_cycle%>"><%=h value.to_s %></td>
<% end %>
代码总行数更多,但如果你打算在整个应用程序中都这样做,效果会更好。beautiful。。。这是助手中应该包含的内容吗?不在部分中?如果您要在多个位置使用此模式,那么是的,我会将其提取到帮助器中。这样比较枯燥,可读性更强。我将在几分钟后添加代码。
def attributes_for(model, match, &block)
model.attributes.each do |key, value|
if key.to_s.include?(match)
# we pass key and value in this example. but you can
# pass whatever you want to the block.
concat(capture(key, value, &block))
end
end
end
<% attributes_for(room, "day") do |key, value| %>
<td class="<%=current_cycle%>"><%=h value.to_s %></td>
<% end %>