Rails - iterate over db entries in one field, separated by linebreaks
-
18-09-2019 - |
Question
In my application I have a products model which has among other things four fields for image paths. I use this to build a slide show.
However, I would love to have all those paths in one big text field and seperate them by whatever works (linebreak would be the easiest to handle in the form).
I was thinking something like:
<% for ... in @screenshots %>
<%= lightbox_to(@product.screenshot, @product.screenshot, "screenshots") %>
<% end %>
and would be hoping for that to result in:
<%= lightbox_to(@product.screenshot1, @product.screenshot1, "screenshots") %>
<%= lightbox_to(@product.screenshot2, @product.screenshot2, "screenshots") %>
<%= lightbox_to(@product.screenshot3, @product.screenshot3, "screenshots") %>
...
Your input is greatly appreciated!
Val
Solution
If you want to have all links in one text field, then you can use split.
<% @product.screenshots.split.each do |screenshot| %>
<%= lightbox_to(screenshot, screenshot, "screenshots" %>
<% end %>
By default it will split on whitespaces. But you can define splitting condition by yourself.
OTHER TIPS
Assuming @product has_many screenshots (and if not, use @screenshots instead of @product.screenshots below).
<% @product.screenshots.each do |screenshot| %>
<%= lightbox_to(screenshot, screenshot, "screenshots") %>
<% end %>
(this assumes lightbox_to is being invoked correctly)
If product really has separate members named 'screenshot1', 'screenshot2', etc., then do this:
<% [:screenshot1, :screenshot2, :screenshot3].each do |screenshot_name|
screenshot = @product.send screenshot_name %>
<%= lightbox_to(screenshot, screenshot, "screenshots") %>
<% end %>`