ActiveRecord query for has_many: through model

How to fulfill a request for companies with a specific branch in relation to has_many: through?

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

"Find all companies with Branch ID 3"

+6
source share
1 answer
 Company.includes(:branches).where(:branches => {:id => 3}) 

or

 Branch.find(3).companies 

UPDATE In fact, there is one drawback of the first fragment: it readily downloads branches along with companies. To avoid this overhead, you can use the left join:

 Company. joins("LEFT JOIN `branch_choices` ON `branch_choices`.`company_id` = `companies`.`id`"). where(:branch_choices => {:branch_id => 3}) 
+13
source

Source: https://habr.com/ru/post/893986/


All Articles