Ecto put_assoc with compsoite foreign key issue


  • Elixir version (elixir -v): 1.8.2
  • Database and version (PostgreSQL 9.4, MongoDB 3.2, etc.): Postgresql 12
  • Ecto version (mix deps): 3.5
  • Database adapter and version (mix deps):3.5
  • Operating system: MAC

Current behavior

Hi I am trying to use put_assoc to work with has_many with composite foreign keys (which is just introduced in ecto 3.5), but didn’t get succedded.
I wonder thus this work out of the box or I need to do a custom injection to put foreign_keys to make it work. Please see my below scenario for more detail.

I have three model -> institution, book and rack

  • institution has books, racks (with has_many)
  • book belongs to institution (with belongs_to)
  • rack belongs to institution with belogs_to
  • book belong to a rack (with composite foreign key to rack and institution, the foreign keys are set to different names than above to avoid the conflicts), with null: true in the migration file.

I am trying to do is like this.

   institution = # I already have an institution in the database
   books = # I already have books in the database belonging to institution
   rack =
     Ecto.build_assoc(institution, :racks)
     |> put_assoc(books)
     ... Other validation  
     |> Repo.insert()

Once I try the above code. Iam getting the issue that for composite foreign_keys that need to references to rack and institution is not assigned and cause the insertion to fail. Could you recommend on how to make put_assoc to work in this scenario.