基于其中一个实例对两组实例进行排序 – 视图 – Ruby on Rails
RoR App有post和类别,主视图是一组类别/post。 它显示每个类别的post(最多3天)。 不显示空类别。
我想对索引视图进行排序,以便首先显示具有更多近期post的类别。 因此,当为类别创建新post时,该类别会上升到应用程序的第一个“行”。 在类别中,post也应该从较新到较旧。
因此,我需要实现两个级别的排序,具有最新post的类别首先和post按类别中的创建日期排序。 我真的被卡住了,你会怎么实现这个?
我的控制器:
def index @categories = Category.includes(:posts).select{|c| c.posts.where(['created_at > ?', 3.days.ago]).count > 0} end
我的看法:
# show category name ?', 3.days.ago]).each do |post| %> # show post title and date
更新:显示到目前为止我尝试过的内容:
我试图首先根据post的creation_date对@categories进行排序(如所解释的,类别has_many:post)。 在我的控制器中:
@categories = Category.includes(:posts).order('posts.created_at').select{|c| c.posts.where(['created_at > ?', 3.days.ago]).count > 0}
然后在我看来,在post加载时对post进行排序:
# show category name ?', 3.days.ago]).each do |post| %> # show post title and date
关于counter_cache sugestion; 我知道这只是为了优化数据库调用,尽管不是绝对必要的。
解决方案 :可以按照之前的UPDATE中的说明完成; 但随着控制器中每个订单(’posts.created_at DESC’)的顺序变化(’posts.created_at’) ; 以及视图中每个订单(’created_at DESC’)的订单更改(’created_at’) 。
你可以试试以下吗? (对不起joins
但会更快)
Category.joins(:posts) .select('categories.*') .group('categories.id') .where('posts.created_at > ?', 30.days.ago) .having('COUNT(posts.*) > 0') .order('posts.created_at DESC')
请参阅原始post中的解决方案。 非常感谢所有公开的贡献者。