I believe the reason is that I want a flexible way to preload data which causes some fields to be sometimes present. To present that as a template I think the main two ways are
- To have one view template to rule them all
- To have one view template per distinct way
The first one sounds better but then I’d need to introduce some utilities to handle the conditional logic which leads me to this type of pattern to handle the fact that if an association is not preloaded, then I don’t want it to show up at all in the response (I don’t want to return nil for a case where we haven’t loaded the data)
def render() do
def render("post.json", %{post: post}) do
%{
id: post.id,
title: post.title,
body: post.body,
comments: render_many(post.comments, CommentView, "comment.json")
}
# it would be nice if we can have it inside the above map but
# since it's a conditional field not sure how
|> maybe_render_association(post.updated_by, :updated_by, User, "basic.json")
end
end
If there’s no better way and these utilities are overall the best approach then I was thinking that maybe it should be built into Phoenix.View






















