Search code examples
elixirecto

How to use a cast value of one field as a default for another field in Ecto


Edit: I guess what I'm asking is how to do: board.members[1].username = owner

I'm trying to make owner of the object (input by user) be among its members, which is a map linking a member name to its role, both being strings. This should happen as the new object is created.

Edit: my sorry attempt at making it simple

defmodule Vision.Boards.Board do
  use Ecto.Schema
  import Ecto.Changeset

  schema "boards" do
    field :members, :map
    field :owner, :string
    field :team_name, :string
    field :title, :string

    timestamps()
  end

  @doc false
  def changeset(board, attrs) do
    board
    |> cast(attrs, [:title, :owner, :team_name])
    |> validate_required([:title, :owner, :team_name])

    board =
      Repo.insert! %Board{members: %{:owner => "Manage"}}
  end
end

Also, this field :members, :map, default: %{:owner => "Manage"}


Solution

  • with Repo.insert you are immediatelly jumping to the database ... why not something like

    board
        |> cast(attrs, [:title, :owner, :team_name])
        |> validate_required([:title, :owner, :team_name])
        |> put_change(:members, %{:owner => "Manage"})
    

    of course in order to handle different behaviour that could/should be extracted to the function and called in the same way ... but for simple create this should do.