开发者

Nested named scopes with joins (explosive error)

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 so开发者_JAVA百科me 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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜