The documentation for the Phoenix scrub_params
method is a little unclear to me. It seems like this functionality is similar to the Rails strong parameters feature. However, when you use it in a controller like so,
plug :scrub_params, "user" when action in [:create]
... you're not explicitly stating which parameters you want to whitelist. I've looked at the code for scrub_params
, but I'm noobish enough with Elixir that I'm not quite sure what's going on.
Is this method just looking at the model and using the required and optional field module attributes for whitelisting parameters?
Also, the scrub_params
documentation says it "Checks to see if the required_key is present". What is the "required key"? Is that just the required fields from the model?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With