hrd*_*rbl 5 activerecord ruby-on-rails
我有一个模型(我们称之为博客)。看起来像:
class Blog < ApplicationRecord
belongs_to :author
def self.foo_all
all.each(&:bar)
end
def bar
author.baz
end
end
Run Code Online (Sandbox Code Playgroud)
现在,我遇到的问题是,当author.blogs.foo_all调用方法时,该类似乎Blog有一个current_scope!这意味着在该author.baz方法内部时,任何查询都Blog具有author查询范围 ( WHERE 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
Run Code Online (Sandbox Code Playgroud)
是的,我可以解决这个问题,为什么要明确删除该范围,但这太出乎意料了!哪个世界不Blog.count执行无范围查询?!
注意:我不在default_scope任何地方使用。
导轨:6.1.3.2
使用 rspec 测试复制问题的代码副本https://github.com/hrdwdmrbl/StockOverflow69020511
| 归档时间: |
|
| 查看次数: |
335 次 |
| 最近记录: |