caslu
Jason encode when associations not loaded
Hello guys! I’m developing an API only Phoenix project for pet donations, and at the moment i have the following schemas:
- User schema:
schema "users" do
field :name, :string
field :email, :string
field :bio, :string
field :avatar, :string
field :website, :string
field :phone, :string
field :social_links, {:array, :string}
field :roles, {:array, Ecto.Enum}, values: [:ADOPTER, :DONOR]
has_many :pets, Announcements.Pet, foreign_key: :owner_id
timestamps(type: :utc_datetime)
end
- Pet schema:
schema "pets" do
field :name, :string
field :size, :decimal
field :bio, :string
field :photos, {:array, :string}
field :age, :integer
field :gender, Ecto.Enum, values: [:MALE, :FEMALE]
field :species, Ecto.Enum, values: [:DOG, :CAT]
field :vaccinated, :boolean, default: false
field :dewormed, :boolean, default: false
field :neutered, :boolean, default: false
field :disability, :boolean, default: false
field :pedigree, :boolean, default: false
field :weight, :decimal
belongs_to :user, Accounts.User, foreign_key: :owner_id
belongs_to :breed, Announcements.Breed, foreign_key: :breed_id
timestamps(type: :utc_datetime)
end
- and the Breed schema:
schema "breeds" do
field :name, :string
field :temperaments, {:array, :string}
has_many :pets, Announcements.Pet, foreign_key: :breed_id
timestamps(type: :utc_datetime)
end
As you can see, the relations above are pretty simple actually, users can own many pets announces and therefore each pet announcement belongs to a user, each pet belongs to a breed, and this specific breed can own a lot announcements, so another many to one relationship.
The problem is around pets and breeds, when i insert a pet, breed or user everything looks fine, but when i trigger the show action on pets_controller the Jason complains that it’s unable to encode because of NotLoaded Association. I know there's questions similars and i know i could preloadthe breeds association with pets, but the weird fact for me is that Jason does not complain if i don't preload the:userassociation, and when i triggershowaction ofuser_controller` Jason does the encoding pretty well even with not loaded pet associations, so what i want to understand is why this error is happening with only one association.
Marked As Solved
D4no0
First of all, ideally you should have a render file where you decide what shape the return will have, it should look the following (this one was generated using mix phx.gen.json Accounts User users name:string age:integer):
defmodule PhoenixTestWeb.UserJSON do
alias PhoenixTest.Accounts.User
@doc """
Renders a list of users.
"""
def index(%{users: users}) do
%{data: for(user <- users, do: data(user))}
end
@doc """
Renders a single user.
"""
def show(%{user: user}) do
%{data: data(user)}
end
defp data(%User{} = user) do
%{
id: user.id,
name: user.name,
age: user.age
}
end
end
There you can dictate what you render, it also decouples your controller from your schema.
As for error you are getting, you cannot render associations that are not preloaded. There are 2 options of doing that:
- Using
Repo.preload/3: Ecto.Repo — Ecto v3.14.0 - Using preload from query: Ecto.Query — Ecto v3.14.0
Otherwise if you don’t need them, don’t render them.
Also Liked
caslu
03juan
Hey no worries. Always helps to include as much code as possible for context from the beginning when getting errors.
Last Post!
dimitarvp
Don’t the *_json.ex and *_html.ex kind of do the same as the view files? I haven’t kept up with Phoenix 1.7.
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
- #forms
- #api
- #metaprogramming
- #security
- #hex









