1

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.

Wesly
  • 343
  • 2
  • 12

2 Answers2

2

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)
br3nt
  • 9,017
  • 3
  • 42
  • 63
0

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

Community
  • 1
  • 1
poramo
  • 546
  • 5
  • 7