【问题标题】:Rails: ActiveRecord Query for has_many :through modelRails:has_many 的 ActiveRecord 查询:通过模型
【发布时间】:2011-10-16 23:33:33
【问题描述】:

如何在“has_many :through”关系中查询具有某个BranchCompanies

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

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

【问题讨论】:

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


    【解决方案1】:
    Company.includes(:branches).where(:branches => {:id => 3})
    

    Branch.find(3).companies
    

    更新 实际上,第一个 sn-p 有一个缺点:它会随公司一起急切地加载分支机构。为了避免这种开销,您可以考虑使用左连接:

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

    【讨论】:

    • 另外,第一行作为 Scope 会是什么样子?
    • scope :filter_by_branch, lambda{|branch_id| includes(:branches).where(:branches => {:id => branch_id})
    猜你喜欢
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    相关资源
    最近更新 更多