凤凰的scrub_params像Rails一样是强参数吗?
Is Phoenix's scrub_params like Rails strong parameters?
Phoenix scrub_params
方法的文档对我来说有点不清楚。看起来这个功能类似于 Rails 强大的参数功能。然而,当你像这样在控制器中使用它时,
plug :scrub_params, "user" when action in [:create]
...您没有明确说明要将哪些参数列入白名单。我查看了 scrub_params
的代码,但我对 Elixir 不够了解,所以我不太确定发生了什么。
这个方法只是查看模型并使用必需和可选的字段模块属性作为白名单参数吗?
另外,scrub_params
文档说 "Checks to see if the required_key is present"。 "required key" 是什么?这只是模型中的必填字段吗?
scrub_params/2 function is not really like Rails strong parameters. In Ecto you define the permitted key in your changeset function using Ecto.Changeset.cast/4.
擦洗参数执行以下操作:
- 确保所需的密钥存在。
- 将具有所需键的 params 映射中的空值更改为
nil
例如,呼叫:
plug scrub_params "user"
将检查是否存在 "user" 密钥。来自 the docs:
If the required_key is not present, it will raise Phoenix.MissingParamError.
如果您有一个如下所示的参数映射:
%{"user" => %{"name" => "foo", "age" => ""}}
然后 "age" 参数将被转换为 nil
。这允许您直接使用参数调用变更集函数:
def create(conn, %{"user" => user_params}) do
User.changeset(user_params)
end
scrub_params/2
与您的模型完全无关,它只适用于 Ecto,因为 Ecto.Changeset.cast/4
函数采用一组必填字段和一组可选字段。将 nil
传递给必填字段将使变更集无效并为该字段添加错误。
Phoenix scrub_params
方法的文档对我来说有点不清楚。看起来这个功能类似于 Rails 强大的参数功能。然而,当你像这样在控制器中使用它时,
plug :scrub_params, "user" when action in [:create]
...您没有明确说明要将哪些参数列入白名单。我查看了 scrub_params
的代码,但我对 Elixir 不够了解,所以我不太确定发生了什么。
这个方法只是查看模型并使用必需和可选的字段模块属性作为白名单参数吗?
另外,scrub_params
文档说 "Checks to see if the required_key is present"。 "required key" 是什么?这只是模型中的必填字段吗?
scrub_params/2 function is not really like Rails strong parameters. In Ecto you define the permitted key in your changeset function using Ecto.Changeset.cast/4.
擦洗参数执行以下操作:
- 确保所需的密钥存在。
- 将具有所需键的 params 映射中的空值更改为
nil
例如,呼叫:
plug scrub_params "user"
将检查是否存在 "user" 密钥。来自 the docs:
If the required_key is not present, it will raise Phoenix.MissingParamError.
如果您有一个如下所示的参数映射:
%{"user" => %{"name" => "foo", "age" => ""}}
然后 "age" 参数将被转换为 nil
。这允许您直接使用参数调用变更集函数:
def create(conn, %{"user" => user_params}) do
User.changeset(user_params)
end
scrub_params/2
与您的模型完全无关,它只适用于 Ecto,因为 Ecto.Changeset.cast/4
函数采用一组必填字段和一组可选字段。将 nil
传递给必填字段将使变更集无效并为该字段添加错误。