RedRoosterMobile
RedRoosterMobile

Reputation: 786

How to do nested preload of models in Phoenix Framework

I have a Phoenix app where I have Polls, that have many Candidates, that have many Votes.

in my controller I load the poll like this:

poll = Repo.get_by!(Poll, url: String.downcase(url))
    |> Repo.preload([:candidates])
# and set it for the view like this
render(conn, "poll.html", poll: poll)

In the view the Candidates are there. The problem is, that the Votes, which belong to a specific Candidate, are not preloaded in the view.

How can I achieve this? What's the syntax for nested preloads?

Upvotes: 1

Views: 906

Answers (1)

Dogbert
Dogbert

Reputation: 222198

To do nested preloads, you can pass nested a nested list as argument like this:

poll = Repo.get_by!(Poll, url: String.downcase(url))
    |> Repo.preload([candidates: [:votes]])

Upvotes: 4

Related Questions