Rails best way to get previous and next active record object

后端 未结 4 1361
野的像风
野的像风 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:05

    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

提交回复
热议问题