开发者

Rails: ActiveRecord Query for has_many :through model

开发者 https://www.devze.com 2023-03-25 10:25 出处:网络
How to query for Companies with a certai开发者_运维知识库n Branch in a \"has_many :through\" relationship?

How to query for Companies with a certai开发者_运维知识库n 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"


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})
0

精彩评论

暂无评论...
验证码 换一张
取 消