How do I add an `.order` invocation to a ActiveRecord collection that I retrieved?
-
31-05-2021 - |
Domanda
I am new in this world of Rails. And I cannot get my head around this problem. How to get @microposts ordered by the date the micropost was created.
This is the line
@microposts = current_user.followeds.map(&:microposts).flatten
I only managed to order by date the 'followeds', but that is not what I am looking for. All the attempts I have made gave me errors, so I guess I am not aware of some syntax.
Any help is welcome!
Soluzione
Normally, you would add an order
clause, as in:
Micropost.where(:written_by => current_user.followeds).order(:created_at)
The way you currently have this line structured doesn't permit that, however, since order
is only available on ActiveRecord::Relations, and once you do map
you no longer have a Relation available to chain on.
If that's the case, you'll want something like:
current_user.followeds.map(&:microposts).flatten.sort_by { |m| m.created_at }
Altri suggerimenti
I think you should try to approach this from another angle.
How about something like this:
@microposts = Micropost.where(author_id: current_user.followed_ids).order(:created_at).all
You might of course have to exchange author_id
for whatever foreign key you have to identify what user a Micropost
was written by.
If you want to reverse the posts (newest first), you just write order("created_at desc")
instead.