Open
Description
assoc
def list_habits(%Account{} = account) do
account
|> assoc(:habits)
|> Repo.all()
end
- Requires
import Ecto, only: [assoc: 2]
- 👎 Pattern-matching (optional, but ideal) requires reference to another context's schema,
Accounts.Account
ids
def list_habits(account_id) when is_integer(account_id) do
account
|> where(account_id: ^account_id)
|> Repo.all()
end
- Requires
import Ecto.Query
- 👍 A tiny bit more efficient, since we only need the ID from the database, not the full record
- 👎 Requires duplicating (potentially complex, with joins) relationship logic
In-Context associations?
Inspired by this forum post.
def list_habits(account_id) when is_integer(account_id) do
%Habits.Account{id: account_id} # not Accounts.Account
|> assoc(:habits)
|> Repo.all()
end
# which requires
defmodule Habits.Habits.Account do
use Ecto.Schema
schema "accounts" do
has_many(:habits, Habit)
end
end
- 👍 Avoids potential duplication of the account <-> habits association logic within this context
- 👍
Habits.Account
could be anything, potentially more context-specific likeHabits.Owner
- 👍 A tiny bit more efficient, since we only need the ID from the database, not the full record
- 👎 Another file?