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