9

How to query for Companies with a certain Branch in a "has_many :through" relationship?

  #company.rb
  has_many :branch_choices
  has_many :branches, :through => :branch_choices

"Find all companies with Branch ID 3"

Promise Preston
  • 24,334
  • 12
  • 145
  • 143
David
  • 937
  • 1
  • 12
  • 22

2 Answers2

16
Company.includes(:branches).where(:branches => {:id => 3})

or

Branch.find(3).companies

UPDATE Actually, there's one downside to the first snippet: it eagerly loads branches along with the companies. To avoid this overhead you may consider using a left join:

Company.
  joins("LEFT JOIN `branch_choices` ON `branch_choices`.`company_id` = `companies`.`id`").
  where(:branch_choices => {:branch_id => 3})
RocketR
  • 3,626
  • 2
  • 25
  • 38
0

The following should do the trick and avoids extra queries:

Company.joins(:branches).where(:branches => {:id => 3})