0

所以我有一个 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 行——我收到一个运行时错误,显示出于某种原因,在运行第二个查询时,它正在维护外部查询的连接范围。真的我需要它自己单独运行,而不与外部查询共享上下文。有什么想法或想法吗?

(我应该提到这个问题是一个“模糊列”错误,因为有一个表是从两个查询中加入的)

4

1 回答 1

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. 通过这种方式,逻辑被包裹在模型中,而不是在控制器中。

于 2010-01-20T20:14:28.607 回答