简体   繁体   English

如何按创建帖子的最后一个人来排序主题?

[英]How to order topics by the last person who created a post?

I have a list of topics and i want to show all topics in the order of the last post. 我有一个主题列表,我想按上一篇文章的顺序显示所有主题。 I think discourse uses something like this when you click on the button latest. 我认为,当您单击最新按钮时,话语将使用类似的内容。

I tried doing this 我尝试这样做

@topics = Topic.includes(:posts).order("posts.created_at desc")

but my topics get in a weird order. 但是我的话题很奇怪。

I would use scopes just because it nicely encapsulates the search functionality into the class to which it belongs so you can reuse it elsewhere. 我之所以使用范围,是因为它很好地将搜索功能封装到了它所属的类中,因此您可以在其他地方重用它。

class Post < ActiveRecord::Base
  scope :descending, ->() { order(arel_table[:created_at].desc) }
end

class Topic < ActiveRecord::Base
  # reuse the descending scope from the Post class to define an
  # order on the Topic class
  scope :descending, ->() {
    joins(:posts).merge( Post.descending )
  }

end

Then you can do: 然后,您可以执行以下操作:

@topics = Topic.descending

If you also want to include the posts in the query you can still do: 如果您还想在查询中包括帖子,您仍然可以执行以下操作:

@topics = Topic.descending.includes(:posts)

You have to use 'joins' instead of 'includes' 您必须使用“联接”而不是“包含”

@topics = Topic.joins(:posts).order("posts.created_at desc")

you can check the explanation here: https://stackoverflow.com/a/6577085/1932629 您可以在此处查看说明: https//stackoverflow.com/a/6577085/1932629

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM