在 Rails 中对分页的 Mongoid 集合进行排序
我在 Rails 应用程序中使用分页 gem (kaminari),并且很难对 Mongo 文档集合进行排序。
首先,我构建查询,即检索用户所有最新评论的一页:
comments = user.comments.desc(:created_at).page(params[:page])
默认情况下,这将为我提供 25 条记录。然后我想呈现每个评论,但现在颠倒顺序,以便最新的评论将位于底部:
comments.asc(:created_at).each do |comment|
- render the comment
但是,通过对我的评论变量调用 asc,它只是重新定义查询并为我提供该用户最旧的评论,而不是最新评论。
如何检索集合并对对象进行排序,而不是简单地更改查询范围?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您在 mongoid 查询上调用 to_a ,它将在此时执行查询。
所以我们调用数组的注释,然后反转数组
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