我有一个模型可以说Post
有一个名为published_at
(datetime)的列。我的模型有两个称为next
和的实例方法prev
。
我正在使用mysql作为数据库适配器。
def next
self.class.unscope(:order).online
.where('published_at > ?', published_at)
.order('published_at ASC').first
end
def prev
self.class.unscope(:order).online
.where('published_at < ?', published_at)
.order('published_at DESC').first
end
使用上面的代码,如果每个帖子都有另一个日期,则导航有效。如果某些帖子在同一日期,则仅显示其中的一条记录。
目标:获取按published_at
日期时间列排序的下一个或上一个记录。
有任何想法吗?
在SQL中,“ next”或“ previous”都没有意义。您必须通过uniq键显式定义排序顺序。例如,如果将非uniq列作为排序基础,则必须添加uniq一。id
然后,您必须更改WHERE子句以接受非uniq列具有相同值的行:
def next
condition = <<~SQL
(published_at = :published_at AND id > :id) OR
(published_at > :published_at)
SQL
self.class.unscope(:order).
online.
where(condition, published_at: published_at, id: id).
order(published_at: :asc, id: :asc).
take
end
prev
构造类似。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句