Search code examples
elixirecto

Preloading assoc in polymorphic structures with elixir/ecto


I have some polymorphic structures named tests, which have teams for which they are defined in common (among other things).

defmodule Test do
  def generate_schema(options, type) do
    quote do
      schema "tests" do
        field :name,                             :string
        field :type,                             :string, default: unquote(type)
        embeds_one :options,                     unquote(options), on_replace: :delete
        many_to_many :teams,                      Team, join_through: "tests_teams", on_replace: :delete
      end
    end
  end

  def get_type_from_module(module) when is_atom(module) do
    module
    |> to_string
    |> String.split(".", trim: true)
    |> List.last
  end

  defmacro __using__(options) do
    type = __CALLER__.module |> get_type_from_module
    quote do
      unquote(generate_schema(options, type))
    end
  end
end

There are a bunch of tests, e.g. TestA

defmodule Tests.TestA do
  defmodule Options do
    embedded_schema do
      field :number_of_jumps, :integer
    end
  end
  use Test, Options
end

The problem is preloading teams for a test, e.g. when I do

Repo.get!(Tests.TestA, id)
|> Repo.preload(:teams)

I get

...
SELECT t0."id", ... , s1."id" FROM "teams" AS t0 INNER JOIN "tests" AS s1 ON s1."id" = ANY($1) INNER JOIN "tests_teams" AS s2 ON s2."test_a_id" = s1."id" WHERE (s2."team_id" = t0."id") ORDER BY s1."id" [[2]]
...
** (Postgrex.Error) ERROR 42703 (undefined_column): column s2.test_a_id does not exist
...

The '...ON s2."test_a_id"...' should be '...ON s2."test_id"...' How can I preload the teams correctly?


Solution

  • The solution seems to be in explicitly defining keys for many_to_many, then it also works for changesets etc.:

    many_to_many :teams, Team, join_through: "tests_teams", join_keys: [test_id: :id, team_id: :id], on_replace: :delete