How do I fill in a column without the need for user (changeset)

How do I insert a value, in an automatic column, when creating a user.
Straight into the changeset?

Ex:
I have a user registration, where the fields (username, email, password)
I need this username to generate automatically, from the email encryption, without the user having to fill it out.

  def generate_string_encrypt(params) do
     params |> :base64.encode
  end

How can I put this function in my changeset?

Current changeset

 schema "users" do
    field :username, :string
    field :email, :string
    field :password, :string
    timestamps()
  end
  def changeset(user, attrs) do
    user
    |> cast(attrs, [:username, :email, :password])
#    |> generate_string_encrypt([:email]) ########  Would it be like this?
  end
  def generate_string_encrypt(params) do
     params |> :base64.encode
  end

How do I have the username filled in automatically, from that function?

it would be something like this:

defp put_password_hash(changeset) do
    case changeset do
      %Ecto.Changeset{valid?: true, changes: %{password: pass}} ->
          put_change(changeset, :password_hash, Bcrypt.hash_pwd_salt(pass))
      _ ->
          changeset
    end
  end

and then call the function where you have |> generate_string_encrypt. Naturally you’ll have to do whatever you need to achieve in your function, I just copied from my own project quick.

Ultimately, that matches on the changeset and allows you to put a change), the most important part here:

put_change(changeset, :password_hash, Bcrypt.hash_pwd_salt(pass))

(in a conference call at the moment but can answer more elaborately later)

It really was what I needed.
Thank you.

1 Like