Previous / Next Links do not work on first and last records in model (rails) -


here model:

def next   self.class.find(:first,     :conditions => ['id > ?', self.id],     :order => 'id')  end  def previous   self.class.find(:first,     :conditions => ['id < ?', self.id],    :order => 'id desc') end 

and code on show page:

   <button align="center" type="button" class="btn btn- btn-xs">             <%= link_to("previous image", pin_url(@pin.next))%>  </button>     <button align="center" type="button" class="btn btn- btn-xs">             <%= link_to("next image", pin_url(@pin.previous)) %> </button> </p>   

this works great unless on first or last record in db. , getting error:

no route matches {:action=>"show", :controller=>"pins", :id=>nil}

how can avoid error when users navigating on first , last record?

you change helper method to

def next_image   self.class.where('id > ?', self.id).order('id asc').first end def previous   self.class.where('id < ?', self.id).order('id desc').first end 

and in view:

<% prev = @pin.previous %> <% next_image = @pin.next_image %>   <%= link_to 'previous image', pin_url(prev) if prev.present? %> <%= link_to 'next image', pin_url(next_image) if next_image.present? %> 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -