Many-to-many association table with extra columns

I don’t have a link as such. I think I used the ebook here a lot: http://pages.plataformatec.com.br/ebook-whats-new-in-ecto-2-0

But basically you have 3 tables. The two “main” tables and an association table. So assume the main tables are “person” and “event”. 1 Person can have many events and one Event can have many versions. They should also have a confirmed field to see if they have confirmed the event or not.

The schemas would look something like this:

schema "person" do
   field :name, :string
   has_many :events, PersonEvent, [on_replace: :delete] % PersonEvent is the module for the association table struct
end

schema "event" do
    field :name, :string
    has_many :people, PersonEvent, [on_replace: delete]
end

schema "person_events" do
   belongs_to :event, Event, references: :event_id
   belongs_to :person, Person, references: :person_id
   field :confirmed, :bool

I quite frequently insert directly into the person_events table, but otherwise just use the schemas as a normal has_many.

5 Likes