"> "> "> "> "> "> "> "> "> 从这样的 fi-6ren">
gpt4 book ai didi

sql - 遍历 rails 中的列

转载 作者:数据小太阳 更新时间:2023-10-29 08:21:47 25 4
gpt4 key购买 nike

这可能非常简单,但我很难弄明白。

我有一部分:

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

从这样的 find_by_sql 结果:

    ID         Room     Day1     Day2   Day3    Day4    Day5    Day6    Day7
18298 Blue Room 13.23 13.23 13.23 13.23 13.23 13.23 13.23

但我不知道会有多少天,我怎样才能遍历不同天数的列结果?

最佳答案

这可以在使用 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 %>

更新:这是帮助示例。如果此模式在您的应用中出现不止一次,我认为这更易于维护和可读。

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

总代码行数更多,但如果您要在整个应用程序中执行此操作则更好。

关于sql - 遍历 rails 中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/993798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com