tomkonidas

tomkonidas

Schemaless Changesets vs Embedded Schemas for Phoenix Forms

While reading Programming Phoenix LiveView, I came across a section (Model Change with Schemaless Changesets - Chapter 5) which goes through setting up schemaless changesets for forms that you do not have a database table for.

I am very familiar with this method (I do it all the time), however instead of creating a Schemaless Changeset, I usually opt to just make an Embedded Schema. To me it seems simpler/cleaner to be able to define the struct and the type at the same time instead of maintaining two things (defstruct and types).


Schemaless

defmodule MyApp.Accounts.User do
  defstruct [:first_name, :email]
  @types %{first_name: :string, email: :string}
end

Embedded

defmodule MyApp.Accounts.User do
  @primary_key false  
  embedded_schema do
    field :first_name, :string
    field :email, :string
  end
end

Question:

Are there any reasons to choose schemaless changesets over embedded schemas?

Most Liked

kingdomcoder

kingdomcoder

Schemaless changeset does not support inputs_for (GitHub Issue).

Please, use embedded schemas. This cost me 3 weeks of work.

redrapids

redrapids

Author of Adopting Elixir

We should probably move Programming Phoenix LiveView to embedded, and talk about the tradeoffs.

LostKobrakai

LostKobrakai

There‘s no need for it to be a module attribute though. The data can come from wherever:

{%{field: nil}, %{field: :integer}}
|> Ecto.Changeset.cast(params, [:field])
…
voughtdq

voughtdq

For Phoenix Forms, no. I always opt for the embedded schema. I have experimented with a kind of Django-like form module where I define, for example, WebWeb.Forms.OnboardingForm and use an embedded schema. Then the save function can run a Multi or just regular stuff from the application modules inside a transaction. It’s kind of nice, but I haven’t decided if it’s the best solution. The idea is that the form is really a web-side concept that just needs to call a few backend functions.

For me, schemaless changesets work well for bulk imports where you want to run data validation and massaging before an insert_all/3. This is mostly for internal use, but I can imagine using it for an API and telling the user which record failed to validate for a better user experience.

Here’s an example, right inside my schema module:

  def schemaless_changeset(attrs) do
    types = Enum.into(__MODULE__.__schema__(:fields), %{}, fn field ->
      {field, __MODULE__.__schema__(:type, field)}
    end)

    {%{}, types}
    |> cast(attrs, Map.keys(types))
  end

Now of course you can just use the actual schema, but it feels “dirty” because you can’t use insert_all/3 on a schema or changeset. So, rather than having apply_changes/1 (or apply_action/2) turn the changeset into a schema then back into a map or keyword list (and forgetting to remove the additional struct fields in the schema ;), I like this approach. As with anything, your mileage may vary.

LostKobrakai

LostKobrakai

Schemaless changesets can be defined at runtime/by code. So it‘s useful when you don‘t have a fixed schema.

Where Next?

Popular in Questions Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement