Phoenix Form default values

Hey everyone,
I’m new to Elixir and Phoenix and I’m currently working on a very simple Phoenix application.
While working on the Form for Users to sing up, a problem came up.
At the moment users can set their own score, but should not be possible.
How can I set a default score for each new user that then gets written to the database?

User sign up would typically have two phases in a User Controller:

  • new prepares the information to be shown on the sign up page.
  • create takes the information entered on the sign up page and prepares it for insertion into the database.

So it would be Accounts.register_user(user_params) (under create) responsibility to set any “default” values. The score wouldn’t be in the user_params as the user can’t set it. But register_user would “know” what default score to set.

I would set this at the database + schema level, so if the field is not present upon creation, it will use that value.

For example:

  • In your schema: field :score, :integer, default: 100, null: false
  • In your DB migration: add(:score, :integer, default: 100, null: false)

If you don’t want users to be able to adjust it during sign up or in other forms, then in your changeset you wouldn’t put score in your list of casted attributes.

Thank you, I might try that later. For now I just removed the field and from the form and in the controller I simply merge the params with a map for the default values, which works great for me.