为了提高性能,我写了以下内容:
a = Address.joins(:vacancies).select('"addresses"."city", COUNT (*) AS total_count').group('"addresses"."city"').order('total_count DESC')
代替:
a = Address.all.keep_if{ |a| a.vacancies.all_active.size > 0 }.uniq{ |a| a.city }.map{ |a| [a.city, a.vacancies.all_active.size] }.sort{ |aa, ab| aa[1] <=> ab[1] }.reverse
但是,该total_count
字段不会显示在结果中。如果我在 sqlite 中运行查询,它会显示出来。我向地址模型添加了一个虚拟属性,但这没有帮助。如何解决这个问题?
另外,这是我的 Rails 控制台输出:
1.9.3p194 :010 > a = Address.joins(:vacancies).select("addresses.city, count(*) as total_count").group("addresses.city").order("total_count DESC")
Address Load (3.9ms) SELECT addresses.city, count(*) as total_count FROM "addresses" INNER JOIN "vacancies" ON "vacancies"."address_id" = "addresses"."id" GROUP BY addresses.city ORDER BY total_count DESC
=> [#<Address city: "Amsterdam">, #<Address city: "Rotterdam">, #<Address city: "Utrecht">, #<Address city: "Den haag">, #<Address city: "Delft">, #<Address city: "Hilversum">, #<Address city: "Amstelveen">, #<Address city: "Rijswijk">, #<Address city: "Breda">, #<Address city: "Zwolle">, #<Address city: "Tilburg">, #<Address city: "Amersfoort">, #<Address city: "Amsterdam centrum">, #<Address city: "Eindhoven">, #<Address city: "Next nature netwerk, amsterdam">, #<Address city: "Almere">, #<Address city: "Ameide">, #<Address city: "Arnhem">, #<Address city: "Baarlo">, #<Address city: "Capelle a/d ijssel">, #<Address city: "De lier">, #<Address city: "Leiden">, #<Address city: "Reigerstraat 16, breda">, #<Address city: "Rottedam">, #<Address city: "'s-hertogenbosch ">, #<Address city: "Alkmaar">, #<Address city: "Alphen aan den rijn">, #<Address city: "Amsterdam singel 137">, #<Address city: "Amsterdam, keizergracht">, #<Address city: "Barendrecht">, #<Address city: "Den haag e.o.">, #<Address city: "Deventer">, #<Address city: "Dordrecht">, #<Address city: "Groningen">, #<Address city: "Gummo, amsterdam">, #<Address city: "Hillversum">, #<Address city: "Houten">, #<Address city: "Lisse">, #<Address city: "Moti, breda">, #<Address city: "Nijmegen">, #<Address city: "Rotterdam ">, #<Address city: "Tuil (waardenburg)">, #<Address city: "Zaltbommel">]
1.9.3p194 :011 > a.first.total_count
=> nil
1.9.3p194 :012 > a.first.to_json
=> "{\"city\":\"Amsterdam\",\"total_count\":null}"