Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With Elixir Ecto, how do I add a has_many relationship in a migration?

Tags:

elixir

ecto

I want to write something like this:

defmodule JobHunt.Repo.Migrations.CompaniesHaveManyJobs do
  use Ecto.Migration

  def change do
    alter table (:companies) do
      add :jobs, :has_many, Job
    end
  end
end

Running mix ecto.migrate with this migration gives an error, so what is the right way to do this?

like image 921
ijt Avatar asked Mar 14 '15 19:03

ijt


People also ask

What does ecto migrate do?

Migration. Migrations are used to modify your database schema over time. This module provides many helpers for migrating the database, allowing developers to use Elixir to alter their storage in a way it is database independent.

What is ecto elixir?

Ecto is an official Elixir project providing a database wrapper and integrated query language. With Ecto we're able to create migrations, define schemas, insert and update records, and query them. Changesets. In order to insert, update or delete data from the database, Ecto. Repo.


2 Answers

Our you could use this way as the documentation recommends:

alter table(:jobs) do
  add :company_id, references(:companies)
end

I'm not sure whether the plural version is required here: references(:companies) but it did not work for me with phermacy (singular)

like image 89
Peter Toth Avatar answered Oct 29 '22 04:10

Peter Toth


You should add the required foreign key to the jobs table:

defmodule JobHunt.Repo.Migrations.CompaniesHaveManyJobs do
  use Ecto.Migration

  def change do
    alter table(:jobs) do
      add :company_id, :integer
    end
  end
end
like image 24
José Valim Avatar answered Oct 29 '22 05:10

José Valim