Best way to handle defaults for embedded schema

I have a schema with an embedded schema.

When a company is first created I want to give them defaults for this schema and embedded schema that they can later change.

  schema "white_labels" do
    field(:subdomain, :string, default: "")

    belongs_to(:company, App.Companies.Company,
      foreign_key: :company_id
    )

    embeds_one(:theme, App.WhiteLabels.Theme) #would like the keys in this map to have defaults

    timestamps()
  end



embedded_schema do
    field(:logo, :string, default: "https://images.unbranded-logo.png")
    field(:favicon, :string, default: "https://images.unbranded-favicon.png")
    field(:background, :string, default: "https://images.unbranded-background.png")
    field(:header_background, :string, default: "https://images.unbranded-header-background.png")
    field(:header_text, :string, default: "#FFF")
    field(:title, :string, default: "#212121")
    field(:text, :string, default: "#212121")
    field(:primary, :string, default: "#5CB85C")
    field(:primary_text, :string, default: "#FFF")
    field(:secondary, :string, default: "#FDD835")
    field(:secondary_text, :string, default: "#2C2C2C")
    field(:tertiary, :string, default: "#003260")
    field(:footer_text, :string, default: "#FFF")
    field(:virtual_card_text, :string, default: "#6F808B")
  end

When my changeset is like the below I get an error saying :theme is required, as expected

  def create_changeset(schema, attrs) do
    schema
    |> cast(attrs, [:subdomain, :company_id])
    |> validate_required([:company_id])
    |> cast_embed(:theme, required: true)
  end

However if I have my changeset as this below I get nil returned for :theme

  def create_changeset(schema, attrs) do
    schema
    |> cast(attrs, [:subdomain, :company_id])
    |> validate_required([:company_id])
    |> cast_embed(:theme)
  end

What’s the best way to implement defaults for an embedded_schema.

Figured this out by passing in an empty map for the :theme key when creating a company

If there are other suggestions I’d love to hear them!

1 Like

Can you show what did you exactly do? I am curious.

I think you could also do something like this:

put_embed(changeset, :theme, %App.WhiteLabels.Theme{})

Note use of put_embed rather than cast_embed for this scenario.

2 Likes