【问题标题】:Nested named scopes with joins (explosive error)带有连接的嵌套命名范围(爆炸性错误)
【发布时间】:2010-01-20 20:03:53
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案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查询。这样逻辑就被封装在模型中,而不是在控制器中。

    【讨论】:

    • 谢谢乔尼!需要注意的是,“with_exclusive_scope”是受保护的(至少在 rails 2.3.2 中),因此要使用它,您需要使用:
       Model.send(:with_exclusive_scope) 
    • 你通常不会在控制器中使用它,我会更新我的帖子来告诉你如何使用它。
    猜你喜欢
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    • 2022-07-10
    • 1970-01-01
    相关资源
    最近更新 更多