Hi all, I am reading the Programming Phoenix book and following the steps to implement the Rumbl webapp.
Then at some steps I try to add something custom to learn a bit more.
So in that application, I have a controller which renders a template like this:
Listing videos
User | Url | Title | Description | Category | |
---|---|---|---|---|---|
<%= video.user_id %> | <%= video.url %> | <%= video.title %> | <%= video.description %> | <%= if category = video.category, do: category.name %> |
<%= link “New video”, to: video_path(@conn, :new) %>
I added this line to render the categories
This is my controller
def index(conn, _params, user) do
videos = Repo.all(user_videos(user)) |> Repo.preload(:category)
render(conn, “index.html”, videos: videos)
end
defp user_videos(user) do
# query user videos
assoc(user, :videos)
end
And when I run a test I wrote, this one:
test “renders index.html”, %{conn: conn} do
videos = [%Rumbl.Video{id: “1”, title: “dogs”},
%Rumbl.Video{id: “2”, title: “cats”}]
content = render_to_string(Rumbl.VideoView, “index.html”,
conn: conn, videos: videos)
assert String.contains?(content, "Listing videos")
for video <- videos do
assert String.contains?(content, video.title)
end
end
It complains with categories not being preloaded
** (KeyError) key :name not found in: #Ecto.Association.NotLoaded
I also tried this:
defp user_videos(user) do
query = (from u in user, select: u.videos, preload: [:category])
Repo.all(query)
end
But not working neither, so how can I preload them?
I thought I just needed to preload them at the pipe with |> Repo.preload(:category)
Also the strange thing is this started to crash with test, without the test it renders the index.html template without any issue