首页 > 解决方案 > 回调 current_scope 后的 ActiveRecord 自定义不为零

问题描述

我有一个模型(我们称之为博客)。看起来像:

class Blog < ApplicationRecord
  belongs_to :author

  def self.foo_all
    all.each(&:bar)
  end

  def bar
    author.baz
  end
end

现在,我遇到的问题是,当调用方法时,该类author.blogs.foo_all似乎有一个!这意味着当在方法内部时,任何查询都具有查询()的范围!Blogcurrent_scopeauthor.bazBlogauthorWHERE authors.id == 123

使用一个例子

这就是发生的事情:

Class Author < ApplicationRecord
  has_many :blogs

  def baz
    id # 456
    blogs.count # "SELECT count(*) FROM blogs WHERE blogs.author_id == 456"
    Blog.count # "SELECT count(*) FROM blogs WHERE blogs.author_id == 456"
    Blog.current_scope # "[Blog id: 123, author_id: 456]"
  end
end

是的,我可以解决为什么要明确删除该范围,但这太出乎意料了!在哪个世界不Blog.count执行无范围查询?!

注意:我不使用default_scope任何地方。

导轨:6.1.3.2

复制问题的带有 rspec 测试的代码副本https://github.com/hrdwdmrbl/StockOverflow69020511

标签: ruby-on-railsactiverecord

解决方案


推荐阅读