Many to Many relationship

Ecto for Beginners : part 17 of 22 published on Sep 07, 2015
$ mix ecto.gen.migration create_tags
# /priv/repo/migrations/TIMESTAMP_create_tags.exs
defmodule Readdit.Repo.Migrations.CreateTags do
  use Ecto.Migration

  def change do
    create table(:taggings) do
      add :post_id, :integer
      add :tag_id, :integer

      timestamps
    end

    create table(:tags) do
      add :title, :string

      timestamps
    end
  end
end
$ mix ecto.migrate
== Running Readdit.Repo.Migrations.CreateTags.change/0 forward
create table taggings
create table tags
== Migrated in 0.2s
# /web/model/tagging.ex
defmodule Readdit.Tagging do
  use Readdit.Web, :model
  import Ecto.Query

  schema "taggings" do
    belongs_to :post, Readdit.Post
    belongs_to :tag, Readdit.Tag

    timestamps
  end

end
# /web/model/tag.ex
defmodule Readdit.Tag do
  use Readdit.Web, :model
  import Ecto.Query

  schema "tags" do
    field :title, :string
    
    has_many :taggings, Readdit.Tagging
    has_many :posts, through: [:taggings, :post]

    timestamps
  end

end
# /web/model/post.ex
defmodule Readdit.Post do
  use Readdit.Web, :model
  import Ecto.Query

  schema "posts" do
    field :title, :string
    field :votes, :integer
    field :flagged, :boolean
    field :posted_on, Ecto.DateTime

    has_many :comments, Readdit.Comment
    has_many :taggings, Readdit.Tagging
    has_many :tags, through: [:taggings, :tag]

    timestamps
  end

end
Next: Reading Many to Many