Search code examples
elixirecto

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


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?


Solution

  • 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