Created
May 3, 2021 18:47
-
-
Save nicolasblanco/69d400adbd858779113bdf02989515ec to your computer and use it in GitHub Desktop.
many_to_many_helper.ex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule ManyToManyHelper do | |
defmacro __using__(_opts) do | |
quote do | |
import Ecto.Query, only: [from: 2] | |
import unquote(__MODULE__) | |
end | |
end | |
defmacro many_to_many_params(opts) do | |
association = Keyword.fetch!(opts, :association) | |
repo = Keyword.fetch!(opts, :repo) | |
module = Keyword.fetch!(opts, :module) | |
quote do | |
def unquote(:"put_#{association}")( | |
%{params: %{unquote("#{association}_ids") => ""}} = changeset, | |
_repo_opts | |
), | |
do: Ecto.Changeset.put_assoc(changeset, unquote(association), []) | |
def unquote(:"put_#{association}")( | |
%{params: %{unquote("#{association}_ids") => ids}} = changeset, | |
repo_opts | |
) do | |
relations = | |
from(r in unquote(module), where: r.id in ^ids) | |
|> unquote(repo).all(repo_opts) | |
Ecto.Changeset.put_assoc(changeset, unquote(association), relations) | |
end | |
def unquote(:"put_#{association}")(changeset, _repo_opts), do: changeset | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment