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 trigger
showaction of
user_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.