Here is how I finally did the query:
Subcontractor.joins(:trades).where('trades.id' => bid.trade_ids).uniq
Question
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.
Solution 2
Here is how I finally did the query:
Subcontractor.joins(:trades).where('trades.id' => bid.trade_ids).uniq
OTHER TIPS
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))