Search code examples
rubyarraysruby-on-rails-3paperclip

Use only the first image if there are multiples


I want to get an understanding of how to achieve the following. I have a simple CMS that will allow you to upload portfolio information/images. The user can upload one image or multiple images.

To show each image I use a .each and iterate through all the images for each portfolio...

<!-- Project Feed -->
    <div class="project-feed clearfix">
     <% @portfolios.each do |p| %>
      <div class="one-third project-item"><!-- add data filter class here to enable selection of sectors-->

       <% p.images.each do |i| %>
        <%= image_tag(i.photo.url(:portfolio_square)) %>
         <div class="overlay">
         <!-- Small image bottom right of overlay, click and can navigate through all images 
          <%= image_tag(i.photo.url(:portfolio_large), :class => 'lightbox-link folio', :rel => 'gallery') %> -->
          <%= link_to p do %>
           <h5><%= p.title %> </h5>
          <% end %>
           <p>
          <%= p.sectors.map(&:name).join(", ") %>
          </p>
         </div><!--/overlay-->
         <h4><%= p.title %></h4>
      </div>
       <% end %>
     <% end %>

My problem is that if there are multiple images assigned to the portfolio (let's say Portfolio 3 has 4 images associated with it) then they all show.

So I want to achieve this layout:

Portfolio 1   Portfolio 2  Portfolio 3  

as opposed to

 Portfolio 1   Portfolio 2  Portfolio 3

 Portfolio 3   Portfolio 3  Portfolio 3

How can I grab only one image if there are multiples? Would this be .first? though I am unsure of the syntax and how it would fit in with my code. Or would I create a separate block and put it in an if statement if the image count is more than 1?


Solution

  • You can use first like this:

    <%= image_tag(p.images.first.photo.url(:portfolio_square)) %>
    

    If you do this you don't need:

    <% p.images.each do |i| %>