Managing Registration Changesets

You’ve already seen a changeset for creating a new user—the one that handles the name and username. Let’s review that now:

 def​ changeset(model, params \\ ​:empty​) ​do
  model
  |> cast(params, ​~​w(name username), [])
  |> validate_length(​:username​, ​min:​ 1, ​max:​ 20)
 end

The Ecto.Changeset.cast function converts that naked map to a changeset and, for security purposes, limits the inbound parameters to the ones you specify. Then, we fire a validation limiting the length of valid usernames to one to twenty characters. Remember, we need to supply :empty parameters instead of an empty map so Ecto can distinguish our blank new changeset from an empty form submission ...

Get Programming Phoenix now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.