Rails best way to get previous and next active record object

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

    This is what order_query does. Please try the latest version, I can help if it doesn't work for you:

    class Product < ActiveRecord::Base
      order_query :my_order,
        [:product_sub_group_id, :asc], 
        [:id, :asc]     
      default_scope -> { my_order } 
    end
    
    @product.my_order(@collection.products).next
    @collection.products.my_order_at(@product).next
    

    This runs one query loading only the next record. Read more on Github.

提交回复
热议问题