2009-06-14 36 views
2

這可能很容易,但我很難搞清楚。在導軌上繞過列

我有一個部分:

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

但我不知道有多少天會有的,我怎麼能環通欄不同日子的結果?

回答

8

這可以在幫助程序中使用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 %> 

更多的代碼總行數,但是如果你要在你的應用程序在做這更好。

+0

美麗......這是應該在幫手嗎?不在局部? – holden 2009-06-14 21:53:40

+0

如果你打算在多個地方使用這種模式,那麼是的,我會提取它到一個幫手。這更幹,更可讀。我會在幾分鐘內添加代碼。 – 2009-06-14 22:06:21

+0

這太棒了。謝謝! – holden 2009-06-14 23:00:10