2012-10-12 31 views
0

目前我有重構代碼迴路

<b>Step 1</b>  
     <%= @recipe_records.instruct_1 %> 
    </p> 
    <p> 
    <b>Step 2</b>  
     <%= @recipe_records.instruct_2 %> 
     </p> 
    ..... 
    <b>Step 30</b>  
     <%= @recipe_records.instruct_30 %> 
     </p> 

我如何把它放在一個循環,而不是列出所有30步的,並不會顯示空的步驟?

<% 30.times do |n|%> 
     <% ri = @recipe_records.instruct_#{n+1}%> 
     <%= if !ri.empty? %> 
      <p> 
      <%= ri %> 
     <% end%> 
    <% end %> 

試過但無法工作。

回答

0

一些fidling後,我已經得到了以下工作代碼:

<% 30.times do |n|%> 
    <% ri = @recipes.send("instruct#{n+1}")%> 
    <% unless ri.blank? %> 
     <p> 
     <b><%= "Step #{n+1}"%></b> 
     <%= ri %> 
     <p/> 
    <% end%> 
<% end %> 
4
<% 30.times do |n|%> 
    <% ri = @recipe_records.send("instruct_#{n+1}")%> 
    <%= unless ri.empty? %> 
     <p/> 
     <%= ri %> 
    <% end%> 
<% end %> 

爲了記錄在案,我不同意你的訪問方法的名字。您應該訪問數組中的時尚的條目,而不必爲每一個訪問者。例如@recipe_records [3],而不是@ recipe_records_3

+0

嗨,該代碼仍然給我的錯誤,SyntaxError錯誤。 'code'er.append =(除非ri.empty?); @ output_buffer.safe_concat(''code'有關信息,.instruct_1到.instruct_30是我的數據庫中的列,不知道如何以正確的方法做這件事,因爲im RoR還很新。 –