2014-09-23 87 views
1

我需要使用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

如下编写查询: -

Event.joins(:project => {:unity => :client}) 
    .group("projects.name, clients.name, events.project_id") 
    .select("projects.name, clients.name, SUM(events.hours)") 
+0

我在与你的建议如下因素的输出:#<的ActiveRecord ::关系[#<事件ID:无>,#<事件ID:无> ]>。我如何获得项目名称,客户名称和活动时间的值?谢谢 – 2014-09-23 19:44:35