Peter Bentley
Peter Bentley

Reputation: 81

How to get prev/next links working in a ROR header

I have a database of artworks and detail pages for each artwork. When I add the following code to my show.html.erb page the links work great. Next takes me to the next artwork, and previous takes me back. When there is no previous, the link disappears and vice versa.

show.html.erb includes

<% if @artwork.next.present?  %>
  <%= link_to "Next &rarr;".html_safe, @artwork.next %>
<% end %>
<% if @artwork.previous.present? %>
  <%= link_to "&larr; Previous".html_safe, @artwork.previous %>
<% end %>

But I really would like to put those links into my header, which is rendered as a partial within my application page. I've noticed, though, that when I copy/paste the links into the partial I get a "NoMethodError in Artworks#index undefined method `previous' for nil:NilClass". I could just use css to move the links up on the page, but that feels janky. What is the right way to get these links working from within the header partial?

Model (artwork.rb) has

  def previous
    Artwork.where(["id < ?", id]).order('rating DESC').last
  end

  def next
    Artwork.where(["id > ?", id]).first
  end

Controller (selected portions)

def index
    if params[:tag] 
      @artworks = Artwork.tagged_with(params[:tag])
    elsif params[:series]
      @artworks = Artwork.tagged_with(params[:series])
    else
      @artworks = Artwork.all
    end
  end

def show
    @artwork = Artwork.friendly.find(params[:id])
end

application.html.erb has

<%= render 'layouts/header' %>

Upvotes: 1

Views: 168

Answers (1)

Philip Hallstrom
Philip Hallstrom

Reputation: 19889

Instead of checking to see if next and previous are present also check to make sure @artwork is present:

<% if @artwork.present?  %>
  <% if @artwork.next.present?  %>                                                                                                                                                                                                                       
    <%= link_to "Next &rarr;".html_safe, @artwork.next %>
  <% end %>
  <% if @artwork.previous.present? %>
    <%= link_to "&larr; Previous".html_safe, @artwork.previous %>
  <% end %>
<% end %>

Upvotes: 1

Related Questions