I have a model and changeset method. I want to have an optional field to which I want to set a default value if it doesn't get passed to chargeset. How can I do that?
Default field values automatically insert the value of a custom field when a new record is created. You can use a default value on a formula for some types of fields or exact values, such as Checked or Unchecked for checkbox fields. After you have defined default values: The user chooses to create a new record.
Changesets are used for creating and modifying your models. A changeset is literally a struct that stores a set of changes (as well as the validation rules.) You pass a changeset to your Ecto Repo to persist the changes if they are valid.
When you create your schema, you can give it a default value by passing it the :default
atom.
schema "foo" do
field :name, :string, default: "bar"
end
Justin's answer is definitely most elegant if your needs are simple, but in my case I needed a little more flexibility. I needed to be able to generate a unique, cryptographically secure value.
I did it in my changeset pipeline:
def changeset(build_proxy, attrs) do
build_proxy
|> cast(attrs, [:avatar, :channel, :username, :service_base_url])
|> gen_api_token_if_empty()
|> validate_required([:avatar, :channel, :username, :service_base_url])
end
defp gen_api_token_if_empty(changeset) do
case get_change(changeset, :api_token) do
nil -> put_change(changeset, :api_token, gen_api_token())
"" -> put_change(changeset, :api_token, gen_api_token())
_ -> changeset
end
end
defp gen_api_token() do
:crypto.strong_rand_bytes(80)
|> Base.url_encode64
|> binary_part(0, length)
end
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