tankh7

tankh7

Help with how to use schema and embedded schema

So this is my first time using embedded schema and I’m having an issue finding information to help me work through how to handle what I need to do in my app.

Basically, a company has the option to white label their site. We’re storing their white label configurations in an embedded schema that we can pull into our front-end applications.

As of now we’re storing the white label information in a white label table in our database and each configuration belongs to a company. I’m unsure of how to handle creating and updating the embedded schema.

defmodule App.WhiteLabels.WhiteLabel do
  @moduledoc false

  use Ecto.Schema
  import Ecto.Changese

  schema "white_labels" do
    field(:subdomain, :string)
    belongs_to(:company, App.Companys.Company
      foreign_key: :company_id
    )
    embeds_one(:themes, App.WhiteLabels.Theme)
    timestamps()
  end

  @doc false
  @spec changeset(%__MODULE__{}, map) :: %Ecto.Changeset{}
  def changeset(schema, attrs) do
    schema
    |> cast(attrs, [:subdomain, :company_id])
    |> validate_required([:subdomain, :company_id])
    |> cast_embed(:themes, required: true)
  end
defmodule App.WhiteLabels.Theme do
  @moduledoc false

  use Ecto.Schema
  import Ecto.Changeset

  embedded_schema do
    field :logo, :string
    field :logo_alt, :string
    field :favicon, :string
    field :background, :string
    field :header_background, :string
    field :header_text, :string
    field :title, :string
    field :text, :string
  end

  @fields [
    :logo,
    :logo_alt,
    :favicon,
    :background,
    :header_background,
    :header_text,
    :title,
    :text,
  ]

  @doc false
  @spec changeset(%__MODULE__{}, map) :: %Ecto.Changeset{}
  def changeset(schema, attrs) do
    schema
    |> cast(attrs, @fields)
  end
end

How would I create a new white label when I need to create %WhiteList{} and %Theme{} at the same time? Does this make sense? Most of the examples I find are adding new embedded schema data to already created data or updating an embedded schema.

First 8 of 8 Posts! Switch mode

thojanssens1

thojanssens1

Not an Ecto expert:) So I guess somewhere in your Context you have:

%WhiteLabel{}
|> WhiteLabel.changeset(attrs)
|> Repo.insert()

and you send the “themes” data alongside the subdomain. Doesn’t that work? What problem are you encountering? What is the structure of the data you are sending to the WhiteLabel changeset function (can you IO.inspect it)?

Sanjibukai

Sanjibukai

Hi,

In my personal current learning path, I don’t yet reach advanced topic like embedded schema (and I even didn’t hear of it until now).

But I already had to deal with similar concern and JSON (or JSONB) field in Postgres works like a charm.
But I admit that (at least when I did it in rails) it was painful to do validation (and even casting values)
IIRC latest version of Rails and Active Records allow virtual attributes but anyway it was somehow difficult to maintain.

But I guess (I mean I hope) that Ecto Changeset can deal easily with store fields in Postgres thanks to cast, or I might be wrong..

BTW interesting to see how you’ll deal with that.
Good luck in the meantime.

dimitarvp

dimitarvp

I think you should correct :themes to :theme. Since you are using plural and you are not supplying extra options then Ecto could be tripped up.

tankh7

tankh7

You’re right, currently I have the following when creating a White Label:

    %WhiteLabel{}
    |> WhiteLabel.changeset(attrs)
    |> Repo.insert()

With what you’re saying I should be fine passing in attrs that look like the following:

    attrs = %{
      company_id: 1,
      subdomain: "acme-corp",
      theme: %{
        logo: "https://image.logo.jpg"
        logo_alt: "Company Logo",
        favicon: "https://image.favicon.favicon.jpg",
        background: "https://image.background.jpg",
        header_background: "#212121",
        header_text: '#FFF',
        title: '#212121',
        text: '#212121'
      }
    }
thojanssens1

thojanssens1

So is it :theme or :themes? The schema field says :themes and in your attrs I see :theme.
And what is the error/result?

tankh7

tankh7

I am going to change :themes to :theme I think as per the comment by @dimitarvp

Sorry I meant to add that in my reply. I’m going to run this now and see what result I get.

tankh7

tankh7

Works well!

Create white label:

    attrs = %{
      company_id: 1,
      subdomain: "acme-corp",
      theme: %{
        logo: "https://image.logo.jpg"
        logo_alt: "Company Logo",
        favicon: "https://image.favicon.favicon.jpg",
        background: "https://image.background.jpg",
        header_background: "#212121",
        header_text: '#FFF',
        title: '#212121',
        text: '#212121'
      }
    }

    %WhiteLabel{}
    |> WhiteLabel.changeset(attrs)
    |> Repo.insert()
dimitarvp

dimitarvp

Glad to hear you made it work.

Let’s be clear: you are free to use whatever names and break conventions – but you’ll have to specify more attributes (configuration) if you do so. That’s why your initial code didn’t work – you didn’t give Ecto the extra configuration options that it expected since your name implied one-to-many association.

You can take a look at Ecto.Schema docs and take it from there (for the future).

Also consider marking one of the comments (yours included) as an accepted answer. It will help future readers.

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
saveman71
Hello ! We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement