ruby-on-rails - 回调 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
似乎有一个!这意味着当在方法内部时,任何查询都具有查询()的范围!Blog
current_scope
author.baz
Blog
author
WHERE authors.id == 123
使用一个例子
- 博客.id == 123
- 作者.id == 456
这就是发生的事情:
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
解决方案
推荐阅读
- c# - 如何在没有异步方法的情况下从 api 下载 pdf 文件
- collision - 当 Kinematic Body 3d (godot) 与网格图、静态体或其他运动体发生碰撞时,如何反弹 Kinematic Body 3d (godot)?
- asp.net-core - 尝试激活“Domain.EntityMaterializerSource”时无法解析“Domain.IBlobModelCache”类型的服务
- c++ - 不能在 cmake 脚本中包含 googletest
- unity3d - Unity中的锚定位置和本地位置有什么区别?
- dataframe - R中的分层数据框->管理空值
- android - flutter_downloader,如何将 url 和 filename 的值从 firebase 获取到此流程中并添加到下载任务列表中?
- java - 将常规 JAR 部署到 Tomcat 服务器
- c# - 如何在 c# Windows Form 中多次使用 DrawLine?
- sqlalchemy - 在 SQLAlchemy 中创建具有关系的对象的正确方法是什么