Preloading Ecto Associations by default

Dania_es picture Dania_es · Apr 13, 2015 · Viewed 8.9k times · Source

Is there any way to preload ecto associations without explicitly using preload:?

Something like an option in the schema?

schema "gadgets" do
  field :foo,
  has_many :bars, Myapp.Bar, preload: true
end

I'm doing something like

Repo.get(Gadget, id)
  |> Repo.preload: [:bars]

Edit: the reason I'm trying to do this is because I want to preload a related model to the already preloaded related model, like

 preload: [:invoices preload: :items] 

Answer

José Valim picture José Valim · Apr 13, 2015

You can also preload as part of a query:

defmodule Gadget do
  use Ecto.Model

  # ...

  def with_invoices(query) do
    from q in query, preload: [invoices: :items]
  end
end

Then:

Gadget
|> Gadget.with_invoices
|> Repo.get!(id)