GVS GVS - 2 months ago 8
Ruby Question

How to display the last third and forth photos with `@photo.last()`

On my user profile, I want to add 4 of the latest photos uploaded by that user. Originally, I had

<%- @user.photos.last(4).each do |photo| %>
. This code works, but it doesn't work with my layout. So I need one row that displays the last 2 photos, while the second row displays the last 3-4 photos.

Here is what I came up with and the line
<%- @user.photos.last(3,4).each do |photo| %>
does not work. I've also tried
(3-4)


<div class="photo-box">
<%- @user.photos.last(2).each do |photo| %>
<a href="<%= user_photo_path(@user.username, photo.id) %>" class="photo-thumbnail">
<div class="photo-mini">
<%= image_tag photo.url %>
</div>
</a>
<% end %>
</div>

<div class="photo-box">
<%- @user.photos.last(3,4).each do |photo| %>
<a href="<%= user_photo_path(@user.username, photo.id) %>" class="photo-thumbnail">
<div class="photo-mini">
<%= image_tag photo.url %>
</div>
</a>
<% end %>
</div>

Answer

You can use the [] method on the photos array.

-1 gets the last element, -2 gets the 2nd to last, and so on.

 @user.photos[-2..-1].each #=> return the last two pictures

Of course, you can simply use the @user.photos.last(2).each in this case.

 @user.photos[-4..-3].each #=> return the last 3-4 pictures. 

This will throw an error unless @user.photos has a length of at least 4, otherwise, you will be trying to access values that does not exist. So, to check for that, you can wrap the div in an if statement.

<% if @user.photos.length >= 2 %>
  <div class="photo-box">
    <% @user.photos.last(2).each do |photo| %>
      ...
    <% end %>
  </div>
<% end %>

<% if @user.photos.length >= 4 %>
  <div class="photo-box">
    <% @user.photos[-4..-3].each do |photo| %>
      ...
    <% end %>
  </div>
<% end %>
Comments