# Scoping problem with :include

**URL:** <https://discuss.rubyonrails.org/t/scoping-problem-with-include/37510>\
**Category:** rubyonrails-core\
**Created:** [December 19, 2008, 1:38am UTC](https://discuss.rubyonrails.org/t/scoping-problem-with-include/37510 "2008-12-19T01:38:02Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Frederick\_Cheung](https://sea2.discourse-cdn.com/rubyonrails/user_avatar/discuss.rubyonrails.org/frederick_cheung/32/3901_2.png) [@Frederick\_Cheung](https://discuss.rubyonrails.org/u/Frederick_Cheung)\
**Post date:** [December 19, 2008, 1:38am UTC](https://discuss.rubyonrails.org/t/scoping-problem-with-include/37510/1 "2008-12-19T01:38:02Z")

</div>

I've been looking at this ticket: [#643 named\_scope with eager loading affects activerecord objects - Ruby on Rails - rails](http://rails.lighthouseapp.com/projects/8994/tickets/643-named_scope-with-eager-loading-affects-activerecord-objects) In a nutshell it's about scoping. If you run

Person.some\_scope.find :all, :include =\> :friends

Then the find on Person happens inside some\_scope, which is fine, but if :friends has class\_name Person (i.e. we have a self referential association) then the query we make to load the friends will also be scoped by some\_scope, which is (I believe undesirable behaviour).

I believe that changing association\_preload.rb to wrap its finds in with\_exclusive\_scope solves the problem. That's what my patch does and it fixes the failing test cases I wrote first. Can anyone think of a case where this would be throwing away scoping we didn't want to throw away? That wouldn't happen in the case above, since were we not eager loading then we;d do

people = Person.some\_scope.find :all people.first.friends...

There's no scoping on the fetch of friends, so my patch brings the eager loaded behaviour in line with the normal version. But what if one was to do

Person.with\_scope(...) do &nbsp;&nbsp;&nbsp;Person.find :all, :include =\> :friends end

Is preloading throwing away the scope when it does its thing going to cause trouble here?

Fred
