archimondain
How to automatically get an empty list when encoding in Jason schema with unloaded associations?
Suppose I have the following:
defmodule Proj.Lecture do
schema "lectures" do
field :title, :string
field :is_active?, :boolean
has_many :list_courses, Proj.Course
end
end
require Protocol
Protocol.derive(Jason.Encoder,
Syntax.Lectures.Lecture,
only: [:title, :is_active?,:list_courses,:id])
Suppose an object Proj.Lecture is loaded from the database without the :list_courses attribute loaded. I would like the Jason encoding to give an empty list in this case.
Is there a way to do that ? (with Jason or Poison).
I currently get an exception :
** (RuntimeError) cannot encode association :list_courses from Proj.Lecture to JSON because the association was not loaded.
Most Liked
LostKobrakai
You should have some place (e.g. a phoenix.view or a function) which applies that assumption. What if later there’s a part in your app which expects courses to be loaded. If you add your logic globally to the json encoding your new code would silently fail.
LostKobrakai
If there’s a decision to be made I don’t really see why it would be boilerplate. Associations not being loaded can just as well be an accident as it can be expected, which is why I feel having an explicit place to handle the conversion of unloaded assocs to an empty list is better then just globally expecting unloaded associations are always expected. If you put the logic in a function this would be one additional function call at the places you encode json data.
benwilson512
Indeed. See: JSON Views in Phoenix | RokkinCat
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









