Skip to content

Instantly share code, notes, and snippets.

@karlosmid
Last active January 24, 2021 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karlosmid/3e687f98d35da97367d4079d961aa92e to your computer and use it in GitHub Desktop.
Save karlosmid/3e687f98d35da97367d4079d961aa92e to your computer and use it in GitHub Desktop.
Ecto Query preload with a query.
@spec author_query() :: Ecto.Query.t()
def author_query() do
from user in User,
select: [:name, :email]
end
@spec query_active_charter_sessions(integer(), NaiveDateTime.t()) :: Ecto.Query.t()
def query_active_charter_sessions(charter_id, active_threshold) do
from(s in Session,
join: c in Charter,
on: c.id == s.charter_id,
where: c.id == ^charter_id,
where: ^active_threshold <= s.inserted_at,
preload: author: ^author_query()
)
end
%Testivator.SRM.Session{
__meta__: #Ecto.Schema.Metadata<:loaded, "sessions">,
author: %Testivator.URM.User{
__meta__: #Ecto.Schema.Metadata<:loaded, "users">,
activation_token: nil,
activation_token_activated_at: nil,
activation_token_expires_at: nil,
auth_tokens: #Ecto.Association.NotLoaded<association :auth_tokens is not loaded>,
charters: #Ecto.Association.NotLoaded<association :charters is not loaded>,
current_sign_in_at: nil,
current_sign_in_ip: nil,
email: "mobber02@test.com",
id: nil,
inserted_at: nil,
last_sign_in_at: nil,
last_sign_in_ip: nil,
name: "Samanta Gorczany",
new_password: nil,
password: nil,
password_hash: nil,
password_reset_token: nil,
password_reset_token_expires_at: nil,
profile: #Ecto.Association.NotLoaded<association :profile is not loaded>,
project: #Ecto.Association.NotLoaded<association :project is not loaded>,
reports: #Ecto.Association.NotLoaded<association :reports is not loaded>,
role: #Ecto.Association.NotLoaded<association :role is not loaded>,
role_id: nil,
session: #Ecto.Association.NotLoaded<association :session is not loaded>,
updated_at: nil
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment