Many to Many relationship in Ecto

Terence Chow picture Terence Chow · Oct 2, 2015 · Viewed 10.3k times · Source

I have a Users model and a Chats model. Intuitively multiple people will belong to the same chat group at any time and each person can have many chat groups. Therefore the chat group must belong to multiple user_id's.

My schema for the chat group and users are:

schema "chatGroups" do
    field :name, :string
    has_many :messages, Message
    belongs_to :user, User

    timestamps
end

schema "users" do
    field :name, :string
    has_many :chatGroups, ChatGroup

    timestamps
end

Any suggestions how to handle this?

Answer

kgpdeveloper picture kgpdeveloper · Jul 6, 2016

This is an old question and the previously accepted answer was no longer the de facto way.

Ecto now supports HABTM or many to many associations.

https://hexdocs.pm/ecto/Ecto.Schema.html#many_to_many/3

many_to_many :users, MyApp.User, join_through: "chat_group_users"