Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: ActiveRecord Query for has_many :through model

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"

like image 777
David Avatar asked Jul 31 '11 16:07

David


1 Answers

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})
like image 175
RocketR Avatar answered Oct 20 '22 19:10

RocketR