quazar
How to encode ecto schema with Jason with all fields
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes. Just want it simple without much config.
@derive {Jason.Encoder, except: [:__meta__, :__struct__]}
I tried this but it failed when association was not loaded. Is there a way I can specify to encode all attributes of schema and association which are preloaded and drop associations which are not loaded.
Most Liked
benwilson512
You’ve tagged this with Phoenix which makes me think you’re doing this in order to render a schema for an API. The suggested approach is to not do this with encoder protocols but rather with JSON views: JSON Views in Phoenix | RokkinCat
scooter
If anyone stumbles across this, the blog post referenced regarding why to use JSON views versus encoder protocols has changed URLs: https://rokkincat.com/blog/2015-03-17-json-views-in-phoenix/
amnu3387
You can define the Jason.Encoder protocol for the structure you want, so that it automatically does that, although I’m not positive this should be done instead of explicitly loading or discarding the fields according to where in the code you’re accessing the records, since this will discard that information always, e.g:
defimpl Jason.Encoder, for: [Your.Module] do
def encode(struct, opts) do
Enum.reduce(Map.from_struct(struct), %{}, fn
({k, %Ecto.Association.NotLoaded{}}, acc) -> acc
({k, v}, acc) -> Map.put(acc, k, v)
end)
|> Jason.Encode.map(opts)
end
end
Notice now that this becomes implicit behaviour whenever Jason’s encode is called on this structure.
Other ways of doing it is to have a function that you call at the end of your load, or explicitly querying with a select, substituting the values explicitly when you don’t need them (this makes it so, that it’s explicit on the code actually running where that step is happening, instead of a catch all) e.g:
YourSchema |> where([ys], ys.id == 1) |> select([ys], %YourSchema{ys | associaton_field: nil}) |> Repo.one
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








