假设我有一个包含id
和sort_number
列的模型产品。
id | sort_number (random)
1 | 325
2 | 161
3 | 58
...
147 | 500 # the biggest sort_number number is equal to the Product.count result
...
500 | 5
我想要Product实例的next(n = 20)
和previous(n = 20)
方法。 IE如果我:
product = Product.find(43)
product.sort_number # => 490
product.next(20) # should return products with sort_number equal to (491..500) + (1..10)
如何实现此功能?如果下次没有更多记录,我怎样才能获得sort_number从1开始的下一条记录?
答案 0 :(得分:0)
好的,我会把它作为答案。
def next id, count
product = Product.find(id)
products = Product.where(
'sort_number > ? AND sort_number <= ?',
product.sort_number, product.sort_number + count
) # this will return 20 requested, unless sort_number is near 500
products |= Product.where(
'sort_number > 1 AND sort_number <= ?',
count - product.count
) if products.count < count
products
end