无法通过与连接表关联来加载范围has_many

时间:2014-02-27 00:24:01

标签: ruby-on-rails ruby-on-rails-4

我使用连接表account_category在帐户和类别之间建立了多对多的关系。在Account类中设置默认关系很简单:

has_many :account_category  
has_many :categories, :through => :account_category

我无法弄清楚的是如何在类别上正确设置其他自定义has_many的范围。

has_many :foobar_categories,
         -> { where type: "foobar" },
         through: :account_category,
         source: :category

这导致无法加载foobar_categories:

# This is a N + 1 query 
Account.includes(:foobar_categories).all.each do
  # do stuff with account.foobar_categories
end

任何人都知道我在这里做错了什么?是否真的不可能通过关联来加载范围的has_many?

编辑:到目前为止,有两个回复建议在类别上使用范围。我不相信类别的范围是正确的,原因有两个:

  1. 在“热切加载关联”部分here中,它表明此应该可以使用作用域关联。
  2. 即使您使用示波器,您如何急切加载关联的范围?
  3. 编辑2:我终于找到了问题的根源。 。隐藏在类中的方法调用,其名称与覆盖关联的关联名称相同。对我的过分表示歉意,并感谢那些花时间回答的人。我正在将这篇文章标记为删除,因为错误在于我们的代码而不是Rails。

2 个答案:

答案 0 :(得分:1)

在模型上定义范围:

class Category < ActiveRecord::Base
  def self.foobar
    where("categories.name = 'foobar'")
  end
end

包含:类别并合并范围:

Account.includes(:categories).merge(Category.foobar).each do |a|
  a.categories.each do |c|
     puts c.created_at
  end
end

答案 1 :(得分:0)

我建议使用范围而不是自定义关联。

范围:foobar_categories - &gt; {includes(:categories).where(name:'foobar')}