在基于Rails 5.2.4.1
的应用程序中,我们想向应用程序中运行的所有查询添加default_scope
。 select
个查询尊重default_scope
,但update_columns
,delete
和update
不尊重default_scope
。
我在3.2
的滑轨中发现了与此相关的一个非常old issue,但在this commit中已修复了它。现在,在Rails 5.2
中,我找不到任何可能的方法。
谢谢。
答案 0 :(得分:0)
all_queries: true
默认作用域选项在 Rails 6.1 之前,如果在模型中定义了 default_scope
,它将仅应用于 select
和 insert
查询。 Rails 6.1 添加了一个选项 all_queries: true
,可以传递给 default_scope
以使作用域适用于所有查询。
default_scope -> { where(...) }, all_queries: true
<块引用>
考虑下面的文章类。
class Article
default_scope -> { where(organization_id: Current.organization_id) }
end
@article.update title: "Hello World"
@article.delete
<块引用>
update
和 delete
方法将生成 SQL 查询,如下所示。正如我们所见,这些查询中缺少 default_scope
。
UPDATE "articles" SET "title" = $1 WHERE "articles"."id" = $2 [["title", "Hello World"], ["id", 146]]
DELETE FROM "articles" WHERE "articles"."id" = $1 [["id", 146]]
<块引用>
在 Rails 6.1 中,我们可以通过将 all_queries: true
传递给 default_scope
来解决这个问题。
class Article
default_scope -> { where(organization_id: Current.organization_id) }, all_queries: true
end
<块引用>
然后生成的SQL变成这样:
UPDATE "articles" SET "title" = $1 WHERE "articles"."id" = $2 AND "articles"."organization_id" = $3 [["title", "Hello World"], ["id", 146], ["organization_id", 314]]
DELETE FROM "articles" WHERE "articles"."id" = $1 AND "articles"."organization_id" = $2 [["id", 146], ["organization_id", 314]]
来源: