DRY ecto relationships with condition

So I have those relationships:

    many_to_many(
      :certifications,
      Certification,
      join_through: "certifier_certifications",
      on_delete: :delete_all,
      on_replace: :delete
    )

    many_to_many(
      :active_certifications,
      Certification,
      join_through: "certifier_certifications",
      where: [is_active: true]
    )

Any chance I can define the :active_certifications relationships over the :certifications one?

Like:

    many_to_many(
      :active_certifications,
      extend: :certifications,
      where: [is_active: true]
    )

Thanks

1 Like

This is precisely a situation where I don’t think relationships are the right way to go, because they simply don’t compose very well. Instead do:

parent |> Ecto.assoc(:certifications) |> Certification.active

# certification.ex

def active(query), do: query |> where(is_active: true)

This allows you to combine it trivially with other queries.

3 Likes