这可以在使用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 %>
代码的总行数越多,但如果你打算在整个应用程序中这样做,效果会更好。