Search code examples
elixirecto

How to implement bidirectional foreign key with ecto


I am new with elixir programming and I am trying to migrate two databases with a foreign key in both tables but it doesn’t seem to work ??

def change do
  create table(:users) do
    add :username, :string
    add :email, :string
    add :name, :string
    add :password, :string
    add :address, :string


    timestamps()
  end

  alter table("users") do
    add :organization, references(:organization)
  end

end

def change do
  create table(:organization) do
    add :org_key, :string
    add :name, :string

    timestamps()
  end

  create unique_index(:organization, [:org_key])

  alter table("organization") do
    add :creator, references(:users)
  end
end

Solution

  • It is unclear why/whatfor do you have two different migrations, but as @sbacarob said in comments, one surely cannot reference inexisting yet table :organizations from the former.

    There is no magic, the code gets executed line by line and one cannot reference something before the declaration. The following would most likely work.

    def change do
      create table(:users) do
        …
      end
    
      create table(:organizations) do
        …
      end
    
      create unique_index(:organizations, [:org_key])
    
      alter table("organizations") do
        add :creator, references(:users)
      end
    
      alter table("users") do
        add :organization, references(:organizations)
      end
    end