2013-03-26 30 views
0

我得到了下面的代碼在我看來:軌從視圖中提取代碼助手(content_tag誤會?)

<ul class="thumbnails"> 
    <% Photo.find_all_by_id(my_params, limit: 10).each do |p| %> 
    <li class="thumbnail"> 
     <%= image_tag(p.url(:fb)) %> 
    </li> 
    <% end %> 
</ul> 

它使得與縮略圖的無序列表。和它的作品沒關係 - 我看到的圖像列表:

<ul class="thumbnails"> 
    <li class="thumbnail"> 
    <img alt="bmw" src="/assets/.../bmw.jpg?1364218949"> 
    </li> 
</ul> 

我希望把它變成幫手,就像這樣:

module PhotosHelper 
    def photos_thumbs_by_ids(photos_ids) 
    content_tag :ul, :class => "thumbnails" do 
     Photo.find_all_by_id(photos_ids, limit: 10).each do |p| 
     content_tag :li, :class => "thumbnail" do 
      image_tag(p.url(:fb)) 
     end 
     end 
    end 
    end 
end 

但是,當我在視圖中使用<%= photos_thumbs_by_ids my_params %>,它只是呈現:

<ul class="thumbnails"></ul> 

我在做什麼錯?

+0

更新:對不起,只是在錯誤的示例中沒有添加params - 我將它發送給幫助者 – 2013-03-26 08:45:07

回答

1

的問題是每個:

Photo.find_all_by_id(photos_ids, limit: 10).each do |p| 
... 
end 

它返回一個數組,而不是字符串。嘗試用「地圖」來收集它,做一個連接

module PhotosHelper 
    def photos_thumbs_by_ids(photos_ids) 
    content_tag :ul, :class => "thumbnails" do 
     Photo.find_all_by_id(photos_ids, limit: 10).map { |p| 
     content_tag :li, :class => "thumbnail" do 
      image_tag(p.url(:fb)) 
     end 
     }.join.html_safe 
    end 
    end 
end 

這是怎麼一回事,因爲至少呈現由有用的方法capture完成。只有當結果是字符串時,此方法纔會放入輸出緩衝區,並且不要嘗試to_s。

+0

是的!剛剛添加.join.html_safe - 它工作 – 2013-03-26 08:58:51

+0

OMG!對不起,我忘了html_safe。 – 2013-03-26 09:01:43

1

我在看到您的代碼後發現,您在調用輔助方法時未通過photo_ids參數。

<%= photos_thumbs_by_ids(photo_ids) %> 

由於沒有ID,以找到照片,所以它返回零級的項目,所以沒有<li>項目將被創建。

1

請嘗試以下操作;

<%= photos_thumbs_by_ids(photo_ids) %> 

def photos_thumbs_by_ids(photos_ids) 
    content_tag :ul, :class => "thumbnails" do 
     Photo.find_all_by_id(photos_ids, limit: 10).each do |p| 
     content_tag :li, :class => "thumbnail" do 
      concat(image_tag(p.url(:fb))) 
     end 
     end 
    end 
    end 
+0

抱歉,只是沒有在示例中誤添加params - 我將它發送給幫助程序 – 2013-03-26 08:44:29