bian2510

bian2510

** (RuntimeError) cannot encode association :address from MyApp.Model.Property to JSON because the association was not loaded

Hi guys I’m having troubles with one preload.

I’m creating one property and I’m adding preloads, but when not have any register for has_one association is returning nil and through this error

     ** (RuntimeError) cannot encode association :address from MyApp.Model.Property to JSON because the association was not loaded.
     
     You can either preload the association:
     
         Repo.preload(MyApp.Model.Property, :address)
     
     Or choose to not encode the association when converting the struct to JSON by explicitly listing the JSON fields in your schema:
     
         defmodule MyApp.Model.Property do
           # ...
     
           @derive {Jason.Encoder, only: [:name, :title, ...]}
           schema ... do

I’ve print the Property created and looks like this

%MyApp.Model.Property{
  __meta__: #Ecto.Schema.Metadata<:loaded, "properties">,
  address: nil,
  currency: "USD",
  description: "Depto 2 ambientes",
  id: 908,
  inserted_at: ~N[2021-05-14 15:29:52],
  price: 260000,
  property_features: nil,
  property_images: [],
  property_type: "department",
  spaces: 2,
  status: true,
  subscriptions: [],
  updated_at: ~N[2021-05-14 15:29:52],
  user: #Ecto.Association.NotLoaded<association :user is not loaded>,
  user_id: 3093
}

I think that this could be for the nil returned in the property?

This is my function to create the property.

  def create_property(user) do
    Repo.insert!(%Property{
      description: "Depto 2 ambientes",
      price: 260_000,
      currency: "USD",
      spaces: 2,
      status: true,
      property_type: "department",
      user_id: user.id
    }) |> Repo.preload([:address, :subscriptions, :property_features, :property_images]) |> IO.inspect
  end

and this is the schema in property.ex

  @derive {Jason.Encoder, except: [:__meta__, :inserted_at, :updated_at, :user]}

  schema "properties" do
    field :spaces, :integer
    field :currency, :string
    field :description, :string
    field :price, :integer
    field :property_type, :string
    field :status, :boolean, default: false
    belongs_to :user, User
    has_one :address, Address
    has_one :property_features, PropertyFeatures
    has_many :subscriptions, Subscription
    has_many :property_images, PropertyImages

    timestamps()
  end

Any have idea where is the problem?

Marked As Solved

al2o3cr

al2o3cr

Repo.preload can handle nested associations. If you need the properties for that User to have a loaded address association, you’d write something like:

|> Repo.preload([properties: [:address]])

Also Liked

al2o3cr

al2o3cr

There’s something odd going on - the printout shows nil in address, but the error message is from inside a protocol implementation for Ecto.Association.NotLoaded:
https://github.com/elixir-ecto/ecto/blob/74a85a99b6dc0fc4667876d5341ad4cafceaa9f6/lib/ecto/json.ex#L2-L6

The code in create_property looks like it should return a correctly loaded association (nil is still “loaded”, just empty), so the next place to investigate is where the result from create_property is used.

al2o3cr

al2o3cr

I suspect the extra [ ] around preloads here is confusing Repo.preload.

Last Post!

bian2510

bian2510

Thank you very much for the help, with this I was able to fix the error.
:slight_smile:

Where Next?

Popular in Questions Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New

Other popular topics Top

Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 44139 214
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New

We're in Beta

About us Mission Statement