Mongoid 中的查询排序无法排序

发布于 2024-12-24 19:57:53 字数 924 浏览 1 评论 0原文

尝试创建一个漂亮的有序列表,我有我知道可以工作的方法,这些方法位于 Participant 类中

def countries_ive_drunk
    had_drinks.map {|drink| drink.beer.country }
  end

  def countries_ive_drunk_count
    countries_ive_drunk.count
  end

知道上面的这些方法可以工作。我创建了一个新类,它想要获取参与者列表并按country_ive_drunk_count对其进行排序,

class Drinkers
  include Mongoid::Document

  def self.top_ten_drinkers
    Participant.order_by([[:countries_ive_drunk_count, :asc]]).limit(10)
  end
end

但是当将其传递到我的haml文件时:

get '/' do
  @topdrinkers = Drinkers.top_ten_drinkers

  haml :index
end

那么它的排序不正确。下面的代码会生成名称旁边带有计数的名称。计数不是升序或降序,而是随机顺序(可能是用户输入 mongodb 的顺序)

  %ul        
    - @topdrinkers.all.each do |participant|
      %li
        = "#{participant.countries_ive_drunk_count} - #{participant.name}"

我是否遗漏了任何明显的内容(幸好这是我第一次使用 ruby​​、mongodb、mongoid、haml...深渊!)

Trying to create a nice ordered list, I have the method which I know work that are which are in the Participant class

def countries_ive_drunk
    had_drinks.map {|drink| drink.beer.country }
  end

  def countries_ive_drunk_count
    countries_ive_drunk.count
  end

Knowning that these above work. I have created a new class which would like to get a list of participants and order it by the countries_ive_drunk_count

class Drinkers
  include Mongoid::Document

  def self.top_ten_drinkers
    Participant.order_by([[:countries_ive_drunk_count, :asc]]).limit(10)
  end
end

but when this is passed down to my haml file:

get '/' do
  @topdrinkers = Drinkers.top_ten_drinkers

  haml :index
end

Then it isn't ordered correctly. and the below code results in names with the count next to them. The counts are not asc or desc, and just in a random order (probably the order the user were entered into mongodb

  %ul        
    - @topdrinkers.all.each do |participant|
      %li
        = "#{participant.countries_ive_drunk_count} - #{participant.name}"

Am I missing anything obvious (be nice its my first time using ruby, mongodb, mongoid, haml... throwing myself in the deep end!)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寄人书 2024-12-31 19:57:53

当您在 Mongoid 中使用 order_bydescasc 时,它会将其传递到 MongoDB 以在数据库服务器上进行排序,并查找字段名为 countries_ive_drunk_count,该名称不存在。您需要将数据存储在 MongoDB 中,以便它能够对所有内容进行排序。

您没有列出太多的架构,但您应该考虑使用组查询来找出饮酒最多的人。

When you use order_by, desc or asc in Mongoid, it's passing it to MongoDB to be sorted on the database server and it's looking for a field named countries_ive_drunk_count, which doesn't exist. You would need to store the data in MongoDB for it to be able to sort everything.

You haven't listed much of your schema, but you should look at using a group query to figure out the top drinkers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文