Ecto has_many :through in form

妖精的绣舞 提交于 2019-12-05 09:05:32

Unfortunately Ecto 1.0 does not support many to many. It means you will need to receive the IDs and manually build the intermediate association for each group you are associating to the user. We hope to make this easier in future releases.

EDIT: Ecto 2.0 supports many_to_many.

The many_to_many association introduced in Ecto 2.0 supports this use case through the join_through option:

: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.

This means you can specify an Ecto schema for the join table and then point to it in the other two schemas, like in the following example:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!