Search code examples
ruby-on-railsruby-on-rails-4rails-activerecordactive-record-query

Search where HABTM is in another model's HABTM


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

  • Here is how I finally did the query:

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