Elixir Ecto: How to write a migration with belongs_to and has_many?
Asked Answered
H

1

13

I have two models, Personand Pet, and I want a Personto be able to have many pets, but a Petto belong to only one person:

defmodule MyApp.Person do
  use MyApp.Web, :model

  alias MyApp.Pet

  schema "persons" do
    field :name, :string
    has_many :pets, Pet
    timestamps()
  end

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [])
    |> validate_required([])
  end
end

and

defmodule MyApp.Pet do
  use MyApp.Web, :model

  alias MyApp.Person

  schema "pets" do
    field :name, :string
    belongs_to :person, Person
    timestamps()
  end

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [])
    |> validate_required([])
  end
end

So, how do I write a migration for that?

defmodule Iloveproblems.Repo.Migrations.CreatePersonsAndPets do
  use Ecto.Migration

  def change do
    create table(:persons) do
      add :name, :string
      # I don't know :( . The has_many stuff
      timestamps()
    end

    create table(:pets) do
      add :name, :string
      # I don't know :( . The belongs_to stuff
      timestamps()
    end
  end
end

I'm using Postgres.

Thanks in advance!

Hymnal answered 9/2, 2017 at 13:17 Comment(1)
add :person_id, references(:persons), null: false and so on as one way to go.Haug
H
17

I guess I will just move my comment here.

In order to create a field that is used as a foreign key, you can write something like this:

add :person_id, references(:persons), null: false

This ensures that the field is not null ( not always necessary ) and that it doesn't break referential integrity.

Haug answered 9/2, 2017 at 15:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.