2014-12-05 89 views
0

我有这些模型:Rails - 如何通过has_many关联获取所有(唯一)数据?

汽车

class Car < ActiveRecord::Base 
    has_many :car_services, dependent: :destroy 
    has_many :services, through: :car_services 
end 

汽车

class CarService < ActiveRecord::Base 
    belongs_to :car 
    belongs_to :service 
end 

服务

class Service < ActiveRecord::Base 
    has_many :car_services 
    has_many :cars, through: :car_services 
end 

我有一个变量保存所匹配的标准,像所有的汽车:

@cars = Car.where('shipped_at = ?', params[:shipped]) 

现在是在@cars保存几辆车和每节车厢都有服务的列表。我正试图获得这些车辆的所有服务的唯一列表,格式为Service A, Service O, Service P

如何做到这一点?有一种方法可遍历所有@cars,然后将每个服务保存到阵列中,然后将该阵列上的电话.uniq_by {|x| x["service_id"]}打印出来,然后将其打印出来。

有没有更有效的方法来做到这一点?我觉得在这个工作流程中是太多的步骤。

预先感谢您。

回答

3

这个工程在轨道4,5(可能更早):

service_ids = CarService.where(car: @cars).pluck(:service_id).uniq 
Service.where(id: service_ids).pluck(:name) 

替代:name为包含字符串的Service字段(根据需要使用.map)。

+0

我相信这应该在rails 3.2中工作,甚至可能是3,但我似乎还记得在3.2中引入了pluck ... – user3334690 2014-12-05 18:26:22

+1

其实我推荐@JiříPospíšil对这个问题的回答,因为他的结果是在单个SQL查询中。 – Matt 2014-12-05 18:30:33

+0

@ user984621我认为马特是正确的。 JiříPospíšil的版本是一个包含子查询的单个查询,但仍然意味着它会以较少的时间击中数据库。 (编辑:对不起,打错了人) – 2014-12-05 18:39:20

2

可以接近从另一个方面的问题,并为此(产生单查询):

Service.joins(:cars).where(cars: {id: Car.where(shipped_at: params[:shipped])}).uniq.pluck(:name) 
+2

Nice - 在单个查询中确认结果。 – Matt 2014-12-05 18:29:31

相关问题