Rails best way to get previous and next active record object

后端 未结 4 1357
野的像风
野的像风 2020-12-03 14:57

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

4条回答
  •  既然无缘
    2020-12-03 15:02

    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.

提交回复
热议问题