I have a Meetup
model that has_many :rsvps
, and Rsvp
model with belongs_to :user
.
Here's my endpoint:
def index(conn, _params) do
one_hour_ago = Timex.now
|> Timex.shift(hours: -1)
|> Timex.to_unix
meetups = from(m in Meetup, where: m.timestamp >= ^one_hour_ago)
|> Repo.all
|> Repo.preload(:rsvps)
render conn, meetups: meetups
end
and my view
def render("index.json", %{ meetups: meetups }) do
render_many(meetups, ParrotApi.MeetupView, "meetup.json")
end
def render("meetup.json", %{ meetup: meetup }) do
%{
id: meetup.id,
rsvped_users: Enum.map(meetup.rsvps, fn rsvp ->
rsvp |> Repo.preload(:user)
user = rsvp.user
%{
image_url: user.image_url,
interests: user.interests,
}
end),
}
end
However, it is failing with ** (Plug.Conn.WrapperError) ** (KeyError) key :image_url not found in: #Ecto.Association.NotLoaded<association :user is not loaded>
It feels wrong to be importing Repo
to a view. Is there a way to do this in the controller?
|> Repo.preload(rsvps: [:user])
in the controller instead? – Dogbert