带连接的嵌套命名范围(爆炸性错误)

时间:2010-01-20 20:03:54

标签: ruby-on-rails activerecord join named-scope

所以我有一个ActiveRecord类,它有几个不同的命名范围,包括连接参数。在运行报告时,我碰巧遇到一个在另一个内部调用的情况:


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

我的问题在第3行 - 我收到一个运行时错误,告诉我由于某种原因,在运行第二个查询时,它会从外部查询维护连接范围。真的,我需要它自己单独运行,而不与外部查询共享上下文。有什么想法或想法吗?

(我应该提一下,问题是“ambigious column”错误,因为有两个查询加入了一个表)

1 个答案:

答案 0 :(得分:1)

您正在寻找

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

这将删除当前正用于该块的任何范围。

示例用法:

# 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

然后使用Model.find_stuff进行查询。这样,逻辑就会包含在模型中,而不是在控制器中。

相关问题