I am using a pagination gem (kaminari) in my Rails app and having a hard time sorting a collection of Mongo documents.
First I structure my query, which is to retrieve one page worth of all the newest comments for a user:
comments = user.comments.desc(:created_at).page(params[:page])
By default this will give me 25 records. I then want to render each comment, but now reverse the order so that the newest comment will be on the bottom:
comments.asc(:created_at).each do |comment|
- render the comment
However, by calling asc on my comments variable, it’s just redefining the query and giving me the oldest comments for that user, not the newest comments.
How can I retrieve the collection and sort that object, rather than simply changing the scope of my query?
If you call to_a on a mongoid query, it will execute the query at that point.
So we’re calling comments to an array, and then reversing the array