通过关联查询订单记录数

时间:2013-04-02 00:18:51

标签: ruby-on-rails ruby-on-rails-3 activerecord

我有两个型号

class Location < ActiveRecord::Base
  has_many :people, :as => :person
end

class People < ActiveRecord::Base
  belongs_to :person, :polymorphic => true
end

我想运行Location where子句。然后我想订购查询,以便首先与其关联的人数最多的位置,然后按降序排列。

Location.where(place: "Waffle House")#Some query attached to this, but what do I write?

如何编写此查询?有可能吗?

解决:解决了解决方案。虽然hacky现在可以工作,直到我可以创建一个SQL语句。基本上循环选定的位置,计算每个位置的人员,并添加一个虚拟属性和人数,并订购哈希数组。

2 个答案:

答案 0 :(得分:0)

查看有关条件连接的Active Record Guide部分,应指向正确的方向。

http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-the-joined-tables

答案 1 :(得分:0)

试试这个:

Location.joins("(
  SELECT person_id location_id, COUNT(1) people_count
  FROM people
  WHERE person_type = 'Location'
  GROUP BY person_id
  ) a ON a.location_id = locations.id"
).order("a.people_count DESC")