salsify/goldiloader

Auto eager loading broken for associations that use unscope

jturkel opened this issue · 4 comments

class Blog < ActiveRecord::Base
  has_many :posts
  has_many :all_posts, -> { unscope(where: :hidden) }, class_name: 'Post'
end

class Post < ActiveRecord::Base
  default_scope { where(hidden: false) }
end

Auto eager loading (and regular eager loading) of Blog#all_posts ignores the unscope.

Corresponding Rails bug is rails/rails#11036. Workaround is to set auto_include = false on the association.

Note this only applies to Rails 4.1 since there was no unscope method before that.

Pushed a change to automatically disable auto eager loading in this case (8ef4fa5). Leaving this bug open so we can remove this workaround when the underlying issue in the Rails preloader is fixed.

Note the Goldiloader workaround doesn't handle the case where a block is passed to ActiveRecord::Base.unscoped e.g.

Post.unscoped do
  Blog.first.posts
end

This should ignore the default_scope on the Post model but it doesn't.

This was fixed in Rails 4.1.9 (via rails/rails@d556939) and Rails 4.2.0 (via rails/rails@0f3cefa). I'm going to remove the Goldiloader workaround for this issue.