2014-12-05 87 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

相關問題