【问题标题】:Rails - iterate over db entries in one field, separated by linebreaksRails - 遍历一个字段中的数据库条目,用换行符分隔
【发布时间】:2011-01-01 17:44:52
【问题描述】:

在我的应用程序中,我有一个产品模型,其中包含四个图像路径字段。我用它来制作幻灯片。

但是,我希望将所有这些路径放在一个大文本字段中,并通过任何有效的方式将它们分开(换行符将是表单中最容易处理的)。

我在想这样的事情:

<% 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") %>  
...

非常感谢您的意见!

【问题讨论】:

    标签: ruby-on-rails iteration line-breaks separator


    【解决方案1】:

    如果您想在一个文本字段中包含所有链接,则可以使用split

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

    默认情况下,它将在空格处拆分。但是你可以自己定义分裂条件。

    【讨论】:

      【解决方案2】:

      假设@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 %>`
      

      【讨论】:

      • 如果屏幕截图的路径在 Product-model 的一个字段中,则不能使用此解决方案
      猜你喜欢
      • 2014-12-05
      • 2013-05-04
      • 1970-01-01
      • 1970-01-01
      • 2014-10-14
      • 2020-04-24
      • 1970-01-01
      • 2016-01-18
      • 1970-01-01
      相关资源
      最近更新 更多