查询关联记录订单号



我有两个模型

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?

我怎么写这个查询?这可能吗?

SOLVED:解决了这个问题。虽然它现在工作,直到我可以创建一个SQL语句。基本上循环遍历选定的位置,计算每个位置的人数,并添加一个带有人数计数的虚拟属性,并对哈希数组进行排序。

看一下活动记录指南中有关条件连接的部分,应该会为您指明正确的方向。

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

试试这个:

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")

最新更新