2015-12-03 62 views
0

我在rails 4上試圖構建一個簡單的幫助程序來減少我的視圖中的一些代碼。Rails 4 - 幫助程序沒有返回任何內容

這裏是使用輔助前視圖代碼(show.html.erb):

<% unless @article.long_effects.blank? %> 
    <ul> 
    <% @article.long_effects.split(';').each do |effect| %> 
     <li><%= effect %></li> 
    <% end %> 
    </ul> 
<% end %> 

和這裏我用於上述代碼構建輔助:

def list(attribute) 
    unless attribute.blank? 
    content_tag(:ul) do 
     attribute.split(';').each do |a| 
     content_tag(:li, a) 
     end 
    end 
    end 
end 

然後我從視圖呼叫這樣的

<%= list(@article.long_effects) %> 

不幸的是,幫手沒有返回任何東西。有什麼建議麼?這是我第一次寫一個返回HTML的助手,所以也許我做錯了什麼?感謝您的幫助。

回答

1

def list(attribute) 
    unless attribute.blank? 
    content_tag(:ul) do 
     attribute.split(';').each do |a| 
     content_tag(:li, a) 
     end 
    end 
    end 
end 

def list(attribute) 
    unless attribute.blank? 
    content_tag(:ul) do 
     attribute.split(';').each do |a| 
     concat content_tag(:li, a) 
     end 
    end 
    end 
end 

concat方法將是從循環條件加入集合對象是有用的。

+0

非常感謝。你能解釋一下concat嗎?困惑爲什麼這使它工作。 @richfisher – Kathan

+0

代碼塊'attribute.split(';')。each {| a | #do something}'return'attribute.split(';')',所以你需要手動連接循環中的內容。 – richfisher