I need to get the previous and next active record objects with Rails. I did it, but don\'t know if it\'s the right way to do that.
What I\'ve got:
Controller
I think it would be faster to do it with only two SQL requests, that only select two rows (and not the entire table). Considering that your default order is sorted by id (otherwise, force the sorting by id) :
@previous_product = Product.where('id < ?', params[:id]).last
@next_product = Product.where('id > ?', params[:id]).first
If the product is the last, then @next_product will be nil, and if it is the first, then, @previous_product will be nil.