Is Phoenix's scrub_params like Rails strong parameters?

♀尐吖头ヾ 提交于 2019-11-30 06:01:49

The 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.

Scrub parameters does the following:

  • Ensure the required key exists.
  • Change empty values from the map in params with the required key to nil

For example, calling:

plug scrub_params "user"

Will check for the presence of a "user" key. From the docs:

If the required_key is not present, it will raise Phoenix.MissingParamError.

If you have a params map which looks like:

%{"user" => %{"name" => "foo", "age" => ""}}

Then the "age" parameter would be converted to nil. This allows you to call your changeset function directly with the params:

def create(conn, %{"user" => user_params}) do
  User.changeset(user_params)
end

The scrub_params/2 is completely unrelated to your model, it just works well with Ecto since the Ecto.Changeset.cast/4 function takes a set of required fields and a set of optional fields. Passing nil to a required field will invalidate the changeset and add an error for the field.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!