我需要使用rails Active Record编写以下查询:
select c.name,p.name,SUM(e.hours)
from Events e, Projects p, Unities u, Clients c
where e.project_id = p.id AND
p.unity_id = u.id AND
u.client_id = c.id
group by c.name, p.name, e.project_id
型号:
class Event < ActiveRecord::Base
belongs_to :project
class Project < ActiveRecord::Base
belongs_to :unity
has_many :events
end
class Unity < ActiveRecord::Base
belongs_to :client
has_many :projects
end
class Client < ActiveRecord::Base
has_one :unity
end
我有类似的东西:
Event.includes(project: [unity: :client])
但我不知道如何指定属性的选择和按部分分组。
答案 0 :(得分:0)
按如下所示编写查询: -
Event.joins(:project => {:unity => :client})
.group("projects.name, clients.name, events.project_id")
.select("projects.name, clients.name, SUM(events.hours)")