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?
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"