Fl4m3Ph03n1x
How to have optional values for an ecto embedded schema?
Background
I am trying to create an embedded schema that needs to save information about orders.
Sometimes orders have no customer_id and that is fine (for the application).
defmodule Order do
use Ecto.Schema
embedded_schema do
field(:customer_id, :integer | nil)
field(:stage, enum: [:bought | :in_shop_cart | :canceled])
field(:details, :string)
end
end
Problem
The issue here is that I get a compile error for customer_id:
(CompileError) misplaced operator |/2
The | operator is typically used between brackets as the cons operator:
[head | tail]
where head is a single element and the tail is the remaining of a list.
It is also used to update maps and structs, via the %{map | key: value} notation,
and in typespecs, such as @type and @spec, to express the union of two types
I understand the issue here is the use of :integer | nil. This is not a list, so the advice I get is not usable.
Question
How can I represent optional values in my embedded schema ? (specifically :something | nil)
Marked As Solved
dimitarvp
All fields are optional by default, you only make them mandatory through validations in a changeset.
Remove the invalid Elixir syntax and you’re good to go.
Also Liked
KiKi
No, you got it right, null: false is for regular schemas, there are also no migrations for embedded schemas.
LostKobrakai
Depending on the database you can use certain constraints for whatever column type is used to back :map. In postgres this would be json/jsonb column and you can e.g. use check constraints to enforce properties on them.
For a topic like this I’d strongly suggest looking at your used database docs just as much as at ecto.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








