darko
darko

Reputation: 321

How can I set some values to some fields in an Ecto model on insert

I have a couple of fields in an Ecto model for which I want to insert a) default value b) generate value when I'm doing an insert. How can I do that? In which function should I do that, in "changeset"?

Upvotes: 2

Views: 2903

Answers (1)

michalmuskala
michalmuskala

Reputation: 11278

Yes, the usual place for such things is the changeset function. If you need to differentiate what happens on insert and update, you can define multiple changeset functions and call the appropriate one when updating or inserting the data. For example:

defmodule MyApp.Schema do
  #...

  def insert_changeset(struct, params) do
    struct
    |> common_changeset(params)
    |> put_change(:foo, "bar") # writing a field to the changeset
    # ...
  end

  def update_changeset(struct, params) do
    struct
    |> common_changeset(params)
    # ...
  end

  defp common_changeset(struct, params) do
    struct
    |> cast(params, [:foo, :bar])
    # ...
  end
end

If the default value is a static one, you can also use ecto's default: option for the field/3 macro in the schema - it's equivalent to providing a value for a field in the defstruct declaration.

Upvotes: 5

Related Questions