Mongoid 中的查询排序无法排序
尝试创建一个漂亮的有序列表,我有我知道可以工作的方法,这些方法位于 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您在 Mongoid 中使用
order_by
、desc
或asc
时,它会将其传递到 MongoDB 以在数据库服务器上进行排序,并查找字段名为countries_ive_drunk_count
,该名称不存在。您需要将数据存储在 MongoDB 中,以便它能够对所有内容进行排序。您没有列出太多的架构,但您应该考虑使用组查询来找出饮酒最多的人。
When you use
order_by
,desc
orasc
in Mongoid, it's passing it to MongoDB to be sorted on the database server and it's looking for a field namedcountries_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.