Rails 3.2 中的 limit 方法和哈希排序的问题 [英] Problems with limit method in Rails 3.2 and hash ordering
问题描述
我有一个包含多个城市的数据库:企业
I have a database with cities which has_many :businesses
我想显示 20 个城市的列表.这20个城市应该是企业最多的城市.仅当拥有至少一项业务的城市少于 20 个时,我才会将人口最多的城市添加到 20 个城市的列表中.由于城市是按我数据库中的居民排序的,在这种情况下,我可以简单地按 id 取第一个.
I want to display a list of 20 cities. These 20 cities should be the ones with the most businesses. Only if there are less than 20 cities with at least one business I add the cities with the most inhabitants to this list of 20 cities. Since the cities are ordered by inhabitants in my database I can simply take the first ones by id in this case.
我现在的查询是:
popularcities = City.order("businesses_count desc").limit(20)
businesses_count 是我数据库中的一列,其中包含该城市的企业数量.
businesses_count is a column in my database with the number of businesses in the city.
现在,我得到了一个按 business_count 排序的 20 家企业的列表,那些企业最多,其他(没有企业)最大,一切似乎都很完美.
Now, I get a list of 20 businesses ordered by businesses_count, those with the most businesses and the others (with no businesses) are the biggest, everything seems perfect.
作为最后一步,我想按名称 asc"对这个 20 个城市的列表进行排序.但是,如果我这样做,Rails 会再次对我数据库中的整个城市列表 (>1.000) 进行排序,而不仅仅是 20 个列表.因此,先前按拥有最多企业的城市进行的排序就会丢失.如果我在最终排序之前使用调试器检查局部变量popularcities",我会得到 20 个条目的正确散列.
As a last step I want to sort this list of 20 cities by "name asc". But if I do so Rails orders the whole list of cities in my database (>1.000) again, not just the list of 20. So the prior sorting by cities with the most businesses gets lost. If I inspect the local variable "popularcities" with a debugger before final sorting I get the correct hash of 20 entries.
我怎样才能确保 Rails 最终只按name asc"排序我的列表 20,而不是包含所有城市的整个数据库?
How can I make sure Rails finally just orders my list 20 by "name asc", not again the whole database with all the cities?
这是我的城市控制器中代码的相关部分:
Here is the relevant part of the code in my cities_controller:
popularcities = City.order("businesses_count desc").limit(20) #gives me a list with the cities I need
@cities = popularcities.order("name asc") #gives me a list of all >1.000 cities sorted by name
推荐答案
只需使用 Ruby 的原生 sort
.
Just use Ruby's native sort
.
popularcities = City.order("businesses_count desc").limit(20)
@cities = popularcities.sort_by(&:name)
这篇关于Rails 3.2 中的 limit 方法和哈希排序的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!