With Elixir Ecto, how to add has_many relationships in 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?

+6
source share
2 answers

You must add the required foreign key to the job table:

 defmodule JobHunt.Repo.Migrations.CompaniesHaveManyJobs do use Ecto.Migration def change do alter table(:jobs) do add :company_id, :integer end end end 
+8
source

Ours, we could use this method, as the documentation recommends:

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

I'm not sure if a plural version is needed here: references(:companies) , but this did not work for me with phermacy (singular)

+8
source

Source: https://habr.com/ru/post/983802/


All Articles