Home Rails loop thru attachments and show the first
Reply: 1

Rails loop thru attachments and show the first

Theopap Published in 2017-11-12 14:30:39Z

I have implemented a basic search and I would like to show each result aligned with an image. I'm using the carrierwave gem on my app and trying loop thru attachments in order to show only the first one as thumbnail.

<div class="container">
  <div class="img-thumbnail" style="display: inline-block;">
    <% if @items.present? %>
        <% @items.each do |item| %>
        <% item.attachments.each do |attachment| %>
            <%= image_tag attachment.url(:mini).first unless attachment.blank? %>
            <% end %>
      <% end %>
   <% end %>

create_table "items", force: :cascade do |t|
  t.string "title"
  t.string "description"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.json "attachments"

But unfortunately the image does not show, no errors etheir just a blank thumbnail. Any ideas how to implement this?

moveson Reply to 2017-11-15 16:06:30Z

In your answer, you iterate over attachments and add an index to the iteration. But the only purpose of the iteration is to choose an attachment whose index == 0. A much easier way to express the same thing is just to retrieve the attachment at index 0 directly using attachments[0]. To be more Ruby-idiomatic, we can use attachments.first.

So we can do away with the inner iteration entirely. All we need is to check if @items is present, then iterate over items, pick the first attachment of each, and retrieve the url.

Here's a simplified version:

<% if @items.present? %>
    <% @items.each do |item|%>
         <%= image_tag item.attachments.first.url(:mini) %>
    <% end %>
<% end %>

Note that this will fail (your code will too) if any item has no attachments. You may want to guard against this by using Ruby's safe-navigation operator (which works in Ruby 2.3+). You can replace the third line with this:

         <%= image_tag item.attachments.first&.url(:mini) %>
# This prevents error if `.first` return nil ^
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.312065 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO