zingo

zingo

I’ll try to describe it as simple as possible.

I made a very simple project to play around with while trying to learn Elixir and Phoenlix Liveview. I created Categories and Products with phx.gen.live. A Product has a belongs_to-relationship with Category, and Category a has_many-relationship with Products.

Adding products and assigning category to them works fine. When hitting the save button the index lists all the products:

In my index-template I have the following code to list it as product name (category name).

<%= product.name %> (<%=product.category.name %>)

Hoever when I click edit on an item and change the category and hit save, the process crashes with the following error:

** (KeyError) key :name not found in: #Ecto.Association.NotLoaded<association :category is not loaded>

After the crashing process restarts everything works fine again, showing the correct new category in the index-view. I also get a quick red flash saying “Something went wrong”.

In live/product_live/index.ex I have modified the mount-function:

def mount(_params, _session, socket) do
  {:ok, stream(socket, :products, Products.list_products_test())}
end

And list_produts_test() is defined as:

def list_products_test do
  Repo.all(Product) |> Repo.preload([:category])
end

I guess I get the error because I have changed the category for one product, and when hitting save somehow the preload() is not called until the process crashes and is reloaded. Should I put the preload() somewhere else, will that solve my problem?

Showing Posts 1 to 6

al2o3cr

al2o3cr

Can you show the code that handles the “save” event?

zingo

zingo OP

I have not modified the generated code, which looks like this:

  def handle_info({TestingWeb.ProductLive.FormComponent, {:saved, product}}, socket) do
    {:noreply, stream_insert(socket, :products, product)}
  end

Edit: Or maybe it’s this function:

  def update_product(%Product{} = product, attrs) do
    product
    |> Product.changeset(attrs)
    |> Repo.update()
  end
al2o3cr

al2o3cr

I suspect the best place to change is the code between these two spots - the part that calls update_product and then sends the {:saved, product} message.

You’d want to add a Repo.preload there to ensure that the Product being added to the stream has the needed association loaded.

zingo

zingo OP

I have now modified my code, it works, but my solution seems a bit sketchy.

First i created a modified version of the generated get_product():

The original:

def get_product!(id), do: Repo.get!(Product, id)

My modified version:

def get_product_2!(id), do: Repo.get!(Product, id) |> Repo.preload([:category])

Then I modified handle_info():

  def handle_info({TestingWeb.ProductLive.FormComponent, {:saved, product}}, socket) do
    product = Products.get_product_2!(product.id) # added this line
    {:noreply, stream_insert(socket, :products, product)}
  end

Would this be the proper way of doing it, or is there a neater way?

al2o3cr

al2o3cr

handle_info already has a Product struct, why Repo.get it again?

zingo

zingo OP

I don’t know how to preload inside handle_info. I tried product = product |> Repo.preload([:category]) which didn’t work. Maybe if I alias Repo it will work. I’ll try that.

Edit: Yes it did work. Still learning, thanks :).

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
psy-q
I’m trying to set up Emacs with elixir-ls via lsp-mode and credo via Flycheck. This should mostly be preconfigured as Flycheck picks up c...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews