Has Many Relationship

Ecto for Beginners : part 15 of 22 published on Sep 07, 2015
$ mix ecto.gen.migration create_comments
* creating priv/repo/migrations
* creating priv/repo/migrations/TIMESTAMP_create_comments.exs
# /priv/repo/migrations/TIMESTAMP_create_comments.exs
defmodule Readdit.Repo.Migrations.CreateComments do
  use Ecto.Migration

  def change do
    create table(:comments) do
      add :content, :text
      add :post_id, :integer

      timestamps
    end
  end
end
$ mix ecto.migrate
== Running Readdit.Repo.Migrations.CreateComments.change/0 forward
create table comments
== Migrated in 0.9s
# /web/models/comment.ex
defmodule Readdit.Comment do
  use Readdit.Web, :model
  import Ecto.Query

  schema "comments" do
    field :content, :string
    
    belongs_to :post, Readdit.Post

    timestamps
  end

end
# /web/models/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

    timestamps
  end

end
Next: Insert child in a one to many relationship