Skip to content

Instantly share code, notes, and snippets.

@vanstee
Last active August 29, 2015 14:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vanstee/3eff11539d170a614848 to your computer and use it in GitHub Desktop.
Save vanstee/3eff11539d170a614848 to your computer and use it in GitHub Desktop.
Chaining Ecto queries using a default query param
defmodule UserQueries do
def in_organization(query \\ User, organization) do
from u in query,
where: u.organization_id == ^organization.id
end
def in_patricks_family(query \\ User) do
from u in query,
where: u.last_name == ^"Van Stee"
end
end
# If we wanted to get users in an organization that are also in Patrick's family,
# we could compose queries on the fly or in a 3rd func like so:
#
# User
# |> UserQueries.in_organization(organization)
# |> UserQueries.in_patricks_family
# |> Repo.all
defmodule UserQueries do
def in_organization(organization) do
from u in User, where: u.organization_id == ^organization.id
|> Repo.all
end
def in_patricks_family do
from u in User, where: u.last_name == ^"Van Stee"
|> Repo.all
end
end
# If we wanted to get users in an organization that are also in Patrick's family,
# we'd have to create a new custom query.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment