Ecto has_many :通过形式

Ecto has_many :through in form

我正在尝试在 Ecto 中建立一个 has_many :through 关系,用于 User 模型和 Group 模型之间的多对多关系。

我能在网上找到的唯一信息是与 José Valim here 的 post 中的嵌套属性有关(顺便说一下,这非常好)。

由于系统中已经存在组,所以我希望进行多个 select 输入。我 运行 在这样做的过程中遇到了几个问题。我不相信可以直接在变更集中分配 groups 关联,因为我每次尝试这样做时都会遇到错误。我的下一个想法是手动完成工作(查找、删除和插入 GroupMembership 记录),但是我不确定这是否是正确的路径,并且想先获得一些建议。

由于代码示例有很多行我做了一个要点here

如果我希望直接在这个问题中 post 它,我当然可以这样做。

感谢大家的帮助!

不幸的是,Ecto 1.0 不支持多对多。这意味着您将需要接收 ID 并为要关联到用户的每个组手动构建中间关联。我们希望在未来的版本中使这更容易。

编辑:Ecto 2.0 支持 many_to_many。

Ecto 2.0 中引入的 many_to_many 关联通过 join_through 选项支持此用例:

:join_through - specifies the source of the associated data. It may be a string, like “posts_tags”, representing the underlying storage table or an atom, like MyApp.PostTag, representing a schema. This option is required.

这意味着您可以为连接指定一个 Ecto 模式 table,然后在其他两个模式中指向它,如下例所示:

defmodule MyApp.GroupMembership do
  use Ecto.Schema
  import Ecto.Changeset

  schema "group_memberships" do
    ...
  end
end

defmodule MyApp.Group do
  use Ecto.Schema
  import Ecto.Changeset

  schema "groups" do
    ...
    many_to_many :users, MyApp.User, join_through: MyApp.GroupMembership
  end
end

defmodule MyApp.Accounts.User do
  use Ecto.Schema
  import Ecto.Changeset

  schema "users" do
    ...
    many_to_many :groups, MyApp.Group, join_through: MyApp.GroupMembership
  end
end