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:

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.

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
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

Other popular topics Top

peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New

We're in Beta

About us Mission Statement