I FIGURED IT OUT. SEE SOLUTION IN REPLY BELOW if anyone else runs into this problem.
I am soooo close to displaying my list of resources in LiveView but struggling to get my LiveView template to show each of the items in the table along with their related table items. The related items are coming in as a list of maps but I can’t seem to access them in order to display them.
It’s a many-to-many case. Resource has many Resource_types. My schema for Resource:
schema "resources" do
field :description, :string
field :title, :string
many_to_many :resource_types, Resourcetype, join_through: "join_resources_resourcetypes"
timestamps()
end
Schema for Resourcetypes:
schema "resource_types" do
field :type, :string
many_to_many :resources, Resource, join_through: "join_resources_resourcetypes"
timestamps()
end
I am preloading in my list_resources() function:
def list_resources do
Resource
|> Repo.all()
|> Repo.preload(:resource_types)
end
When I do IO.inspect on the list of preloaded resources, I can see it has the related resource_types:
%SketchLinks.Resources.Resource{
__meta__: #Ecto.Schema.Metadata<:loaded, "resources">,
description: "Still workss",
resource_types: [
%SketchLinks.Resourcetypes.Resourcetype{
__meta__: #Ecto.Schema.Metadata<:loaded, "resource_types">,
id: 2,
inserted_at: ~N[2021-03-27 22:08:32],
resources: #Ecto.Association.NotLoaded<association :resources is not loaded>,
type: "Blog",
updated_at: ~N[2021-03-27 22:08:32]
},
%SketchLinks.Resourcetypes.Resourcetype{
__meta__: #Ecto.Schema.Metadata<:loaded, "resource_types">,
id: 3,
inserted_at: ~N[2021-03-27 22:08:32],
resources: #Ecto.Association.NotLoaded<association :resources is not loaded>,
type: "Video",
updated_at: ~N[2021-03-27 22:08:32]
}
],
title: "Still workss",
}
BUT … when I go to display in my template, I get an error. Here is the code from my template:
<%= for resource <- @resources do %>
<tr id="resource-<%= resource.id %>">
<td><%= resource.title %></td>
<td><%= resource.description %></td>
<td><%= resource.resource_types.type %><td> *** THIS IS MY RELATION ***
ERROR:
** (exit) an exception was raised:
** (ArgumentError) argument error
:erlang.apply([%MyProject.Resourcetypes.Resourcetype{__meta__: #Ecto.Schema.Metadata<:loaded, "resource_types">, id: 2, inserted_at: ~N[2021-03-27 22:08:32], resources: #Ecto.Association.NotLoaded<association :resources is not loaded>, type: "Blog", updated_at: ~N[2021-03-27 22:08:32]}], :type, [])
I get that this is a many-to-many relationship so resource.resource_types is returning a list of resource_types. So I need to somehow get into that list and grab the “type” name from each map in that list and concatenate them into a string. I’ve tried “get_in” and for-loops but can’t get my hands on the resource_type.type in order to display it in my template. I get various errors every time I try to access “type” from resource.resource_type.
How do I get my hands on those associated relations to display them in my template?