Skip to content

assoc vs. ids: should contexts reach into other contexts? #37

Open
@stevegrossi

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 like Habits.Owner
  • 👍 A tiny bit more efficient, since we only need the ID from the database, not the full record
  • 👎 Another file?

Metadata

Assignees

No one assigned

    Labels

    styleNon-functional changes related to coding style

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions