문제

I have two models, Subcontractor:

class Subcontractor < ActiveRecord::Base
  has_and_belongs_to_many :trades
end

And Bid:

class Bid < ActiveRecord::Base
  has_and_belongs_to_many :trades
end

I'm trying to find all subcontractors who have trades that match the trades of a particular bid. I've tried something along the lines of Subcontractor.where(trade_ids: bid.trade_ids) but that doesn't seem to work.

도움이 되었습니까?

해결책 2

Here is how I finally did the query:

Subcontractor.joins(:trades).where('trades.id' => bid.trade_ids).uniq

다른 팁

If you pass an array to an ActiveRecord query, ActiveRecord is smart enough to know that you mean all items IN the array.

Have you tried

Subcontractor.where(trade_ids: bid.trades.pluck(:id))

You can do it in this way also

Subcontractor.where("trade_id in (?)", bid.trades.pluck(:id))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top