Best Practice: Preloading Partial Associations

I do have Posts that are written by Users. I do only need the name field of the user when preloading the assoc.

Either I can optimize the preload query:

user_query = from(u in User, select: u.name)
from( p in Post, preload: [user: ^user_query])
|> Repo.all()

or I can load the entire user and then select only the name in rendering my view:

from( p in Post, preload: [:user])
|> Repo.all()

def render("post.json", %{post: p}) do
  %{
    #other post fields i need
    user: p.user.name
  }
end

What is generally considered a better practice and why?
Would it make a difference in performance?

A join() is probably better for you.

2 Likes