views:

222

answers:

1

So I have an ActiveRecord class with a couple different named scopes that include join parameters. While running a report, I happen to have a situation where one gets called inside of the other:


1 Model.scope_with_some_joins.find_in_batches do |models|
2   models.each do |mdl|
3     other_comparisons = Model.scope_with_other_joins
4   end
5 end

My problem is on line 3 -- I get a runtime error showing me that for some reason when running the second query it's maintaining the join scope from the outer query. Really I need it to be run separately on it's own, without sharing context with the outer query. Any thoughts or ideas?

(I should mention that the problem is an "ambigious column" error because there is one table that is joined in from both queries)

+1  A: 

You're looking for

Model.with_exclusive_scope { ...do your find in here... } 

This will remove any scopes that are currently in use for the block.

An example usage:

# in model.rb
def self.find_stuff
  self.scope_with_some_joins.find_in_batches do |models|
    models.each do |mdl|
      self.with_exclusive_scope do
        other_comparisons = self.scope_with_other_joins
      end
    end
  end
end

Then you query with Model.find_stuff. This way the logic is wrapped up in the model, not in the controller.

jonnii
Thanks jonnii! One note is that "with_exclusive_scope" is protected (at least in rails 2.3.2) so to make use of it you need to use:<pre><code> Model.send(:with_exclusive_scope)</code></pre>
Ethan Vizitei
You wouldn't usually use it within a controller, i'll update my post to show you how to use it.
jonnii