Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for a field in changeset

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?

like image 786
Kooooro Avatar asked Nov 29 '16 07:11

Kooooro


People also ask

What is the default value of a field?

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.

What is a changeset in Elixir?

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.


2 Answers

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
like image 161
Justin Wood Avatar answered Sep 30 '22 12:09

Justin Wood


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
like image 23
Freedom_Ben Avatar answered Sep 30 '22 14:09

Freedom_Ben