/ /子モデルに2つの属性がある場合-ruby-on-rails

子モデルに2つの属性がある場合-ruby-on-rails

じぶんの Driver モデルhas_many Workables

のリストを要求するにはどうすればよいですか Drivers ある workable どこ vehicle_idx そして has_vehicletrue

ドン "t 含めたい Drivers 2つの実行可能ファイルがあり、そのうちの1つには正しい vehicle_id、および他の has_vehicle == true

理想的には、おそらくこれのスコープが必要です。

私は次のことを試しましたが、レコードが返されません。 Driver.rb

  scope :has_vehicle, -> (vehicle) {
joins(:workables).
where("workables.vehicle_id = ?", vehicle).
where("workables.has_vehicle = ?", true) }

私はこのようなアプローチをとることができますが、それは非常に遅いように見えます:

   arr = []
Workable.where(vehicle: x).where(has_vehicle == true).each do |e|
arr += e.drivers.map(&:id)
end
@drivers = @drivers.where(id: arr)

熱心な読み込みを使用する場合、上記は高速ですか?

回答:

回答№1は0

機能的でかなり高速な方法を見つけました:

driver_ids = Workable.where(driver_id: @drivers.collect(&:id)).where("vehicle_id = ? and has_vehicle = ?", params[:vehicle].to_i, true).collect(&:driver_id)
@drivers = @drivers.where(id: driver_ids)