Help with assoc and preload

I have a vanilla liveview project with two schemas. These were created with mix phx.gen.live and I’ve added all the routes and I am able to create categories and items correctly. I can view the categories in the list view and print associated item titles. The issue comes when viewing a single Category, where I get the following error:

protocol Phoenix.HTML.Safe not implemented for %Organiser.Categories.Category{meta: ecto.Schema.Metadata<:loaded, “categories”>, id: 1, inserted_at: ~N[2021-04-13 08:09:42], items: [%Organiser.Items.Item{meta: ecto.Schema.Metadata<:loaded, “items”>, category: ecto.Association.NotLoaded, category_id: 1, id: 1, inserted_at: ~N[2021-04-13 08:35:33], title: “test item”, updated_at: ~N[2021-04-13 08:35:33]}], title: “Category A”, updated_at: ~N[2021-04-13 08:09:42]} of type Organiser.Categories.Category (a struct). This protocol is implemented for the following type(s): Decimal, Phoenix.LiveView.Component, Phoenix.LiveComponent.CID, Phoenix.LiveView.Comprehension, Phoenix.LiveView.Rendered, Tuple, Float, BitString, NaiveDateTime, Phoenix.HTML.Form, DateTime, Date, Integer, Time, Atom, List

The schemas are as follows:

schema "categories" do
    field(:title, :string)
    has_many(:items, Organiser.Items.Item)

    timestamps()
  end

schema "items" do
    field :title, :string
    belongs_to(:category, Organiser.Categories.Category)

    timestamps()
  end

The list_categories looks like this

def list_categories do
    Repo.all(
      from(c in Category,
        left_join: i in assoc(c, :items),
        preload: [items: i]
      )
    )
  end

and the get_category like this

 def get_category!(id) do
    Repo.get!(Category, id)
    |> Repo.preload(:items)
  end

I’m just not able to figure out the correct way to get a single category with all its associated items. In the template I simply trying to show the single category at the moment with <%= @category %>

Any help would be appreciated.

Hello,

You need to use inspect/1: <%= inspect(@category) %> to render the struct in the template

2 Likes

This is definitely one of those facepalm moments. Thanks, that works perfectly

1 Like

It’s a common mistake I do all the time. One of my error logs’ best friends :wink: