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?