2010-01-05 50 views
0

在我的應用程序中,我有一個產品模型,其中包含四個圖像路徑字段。我用它來建立幻燈片。然而,我希望在一個大文本字段中擁有所有這些路徑,並且通過任何作品將它們分開(linebreak將是最容易處理的形式)。Rails - 遍歷一個字段中的數據庫條目,用換行符分隔

我的想法是這樣的:

<% for ... in @screenshots %> 
    <%= lightbox_to(@product.screenshot, @product.screenshot, "screenshots") %> 
<% end %> 

,並會希望是導致:

<%= lightbox_to(@product.screenshot1, @product.screenshot1, "screenshots") %> 
<%= lightbox_to(@product.screenshot2, @product.screenshot2, "screenshots") %> 
<%= lightbox_to(@product.screenshot3, @product.screenshot3, "screenshots") %> 
... 

您的意見是非常感謝!

纈氨酸

回答

1

如果你想要在一個文本字段中包含所有鏈接,那麼你可以使用split

<% @product.screenshots.split.each do |screenshot| %> 
    <%= lightbox_to(screenshot, screenshot, "screenshots" %> 
<% end %> 

默認情況下,它將在空格上分割。但是你可以自己定義分裂條件。

0

假設@product的has_many截圖(如果沒有,使用@screenshots代替@ product.screenshots下文)。

<% @product.screenshots.each do |screenshot| %> 
    <%= lightbox_to(screenshot, screenshot, "screenshots") %> 
<% end %> 

(假定lightbox_to被正確調用)

如果產品確實有一個名爲 'screenshot1' 單獨成員, 'screenshot2' 等等,那麼這樣做:

<% [:screenshot1, :screenshot2, :screenshot3].each do |screenshot_name| 
    screenshot = @product.send screenshot_name %> 
    <%= lightbox_to(screenshot, screenshot, "screenshots") %> 
<% end %>` 
+0

您無法使用此解決方案,其屏幕截圖的路徑合併在產品模型的一個字段中 – jigfox 2010-04-21 18:08:53