Rails best way to get previous and next active record object

Write these methods in your Product model:

class Product

  def next
    self.class.where("id > ?", id).first
  end

  def previous
    self.class.where("id < ?", id).last
  end

end

Now you can do in your controller:

@product = Product.friendly.find(params[:id])

@previous_product = @product.next
@next_product = @product.previous

Please try it, but its not tested.
Thanks

Leave a Comment