ActiveRecord查询has_many:通过模型

时间:2011-07-31 16:59:29

标签: ruby-on-rails-3 activerecord has-many-through

如何在“has_many:through”关系中使用某个分支查询公司

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

“查找分支机构ID为3的所有公司”

1 个答案:

答案 0 :(得分:14)

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

Branch.find(3).companies

<强>更新 实际上,第一个片段有一个不利因素:它急切地将分支机构与公司一起加载。为避免这种开销,您可以考虑使用左连接:

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