silverdr
Embedded schema and JSONB
This is an example from one of the very useful “FullstackPhoenix” tutorials, namely:
# lib/tutorial/shop/data.ex
defmodule Tutorial.Shop.Data do
use Ecto.Schema
import Ecto.Changeset
@primary_key false
embedded_schema do
field :size, :string
field :color, :string
end
@doc false
def changeset(option, attrs) do
option
|> cast(attrs, [:size, :color])
|> validate_required([])
end
end
When saving the record, which embeds_one of the above, the whole “embedded_schema” gets stored, including fields, which are not set. This seems to make sense to me. At least as default behaviour. Out of curiosity – the question: is there a switch/option/other simple method, which would make it store only the fields, which are actually used/set?
Marked As Solved
evadne
You could write a custom Ecto type which only stores fields which are not nil. The wire protocol is forgiving. Your custom type can have a type of :map. In dump/1 you can emit a trimmed-down Map.
Last Post!
silverdr
I don’t think it’s worth the effort in the case I have at hand. Was curious if somebody thought of such scenario and maybe provided an option OOB. But yes, if dumping whole maps becomes an issue then such custom type might help, TNX.
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
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









