# 将\`scope:\`向序列化器树下传递：就这样做，还是不呢？

**URL:** <https://meta.discourse.org/t/forwarding-the-scope-down-a-tree-of-serializers-just-do-it-or-not/353691>\
**Category:** Development\
**Created:** [2025年二月21日 21:02 UTC](https://meta.discourse.org/t/forwarding-the-scope-down-a-tree-of-serializers-just-do-it-or-not/353691 "2025-02-21T21:02:56Z")\
**Posts on this page:** 1\
**Showing post:** 1

<div class="post-metadata">

**Author:** ![mdoggydog](https://avatars.discourse-cdn.com/v4/letter/m/82dd89/32.png) [@mdoggydog](https://meta.discourse.org/u/mdoggydog)\
**Post date:** [2025年二月21日 21:02 UTC](https://meta.discourse.org/t/forwarding-the-scope-down-a-tree-of-serializers-just-do-it-or-not/353691/1 "2025-02-21T21:02:56Z")

</div>

序列化器可以通过 `scope:` 参数提供，该参数旨在为序列化器提供权限上下文。在 Discourse 代码中，提供的范围是 `Guardian`，并且似乎每个序列化器都旨在接收 `Guardian` 作为其范围。`ApplicationController`（所有控制器的基类）维护一个 `Guardian`，并且有多种机制来确保 `Guardian` 作为所有序列化器的 `scope:` 被注入。

但是，并非所有场景都涵盖在这些机制中。每当显式构造序列化器时，例如调用 `ActiveModel::ArraySerializer.new(...)`，就需要手动注入范围。确实，大多数 `XxxxSerializer.new(...)` 的实例在参数列表中都有 `scope: scope` 或 `scope: guardian`。但并非所有实例都如此。

所以，我的问题是：这里的开发理念是什么？是：

1. 范围应该始终转发（除非有特定原因不这样做）；如果有人忘记这样做，那就是一个潜在的错误，应该通过添加适当的 `scope: ...` 来修复；或者
2. 是的，没关系；有人会在实际破坏某人的东西时修复那些地方。

在我的例子中，我向 `BasicUserSerializer` 添加了一个 `scope` 的用法……然后当我发现它破坏了 Chat 中的内容时，我感到非常困惑……（经过大量挖掘后）我终于意识到，这是因为链中的某个序列化器 `XxxSerializer -> YyySerializer -> ... -> BasicUserSerializer` 没有转发范围！

---

_[View the full topic](https://meta.discourse.org/t/forwarding-the-scope-down-a-tree-of-serializers-just-do-it-or-not/353691)._
