パフォーマンスを向上させるために、私は次のように書いています。
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}"