我有一些名为tests的多态结构,它们具有共同定义的团队(除其他外)。
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
有许多测试,例如种皮
defmodule Tests.TestA do
defmodule Options do
embedded_schema do
field :number_of_jumps, :integer
end
end
use Test, Options
end
问题是预测团队进行测试,例如当我做的时候
Repo.get!(Tests.TestA, id)
|> Repo.preload(:teams)
我得到了
...
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
...
' ... ON s2。" test_a_id" ...'应该是' ... ON s2。" test_id" ...' 我怎样才能正确预装团队?
答案 0 :(得分:0)
解决方案似乎明确地defining keys for many_to_many, 那么它也适用于变更集等:
many_to_many :teams, Team, join_through: "tests_teams", join_keys: [test_id: :id, team_id: :id], on_replace: :delete