Rails - 如何通过has_many关联获取所有(唯一)数据?

时间:2014-12-05 17:16:26

标签: ruby-on-rails ruby arrays unique 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"]}然后将其打印出来。

有更有效的方法吗?我认为在这个工作流程中步骤太多了。

提前谢谢。

2 个答案:

答案 0 :(得分:3)

这适用于Rails 4(可能更早):

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

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

答案 1 :(得分:2)

您可以从另一方面解决问题并执行此操作(导致单个查询):

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