Foreign key constraint error

I am handling foreign key constraint error with the code:

        record
      |> Ecto.Changeset.change()
      |> Ecto.Changeset.foreign_key_constraint(:users, name: :users_facilities_facility_id_fkey,
         message: "are still associated with id"
       )

Its working fine. But throw an error if I remove name .Is there a way that i don’t have to use the name: users_facilities_facility_id_fkey. I done want to explicitly tell it every time the name of the foreign key. In docs its says name feild is optional

Its working fine with no_assoc_constraint without the name field but throws an error with the foreign_key_constraint.

Any suggestions?

Thanks

Seems like the default would work for you if the foreign key constraint was named :users_facilities_facilities_id_fkey.

its named exactly this: :users_facilities_facilities_id_fkey

Are you sure? Your sample code has it as :users_facilities_facility_id_fkey. Note the second “facility”.

Yeah sorry . its :users_facilities_facility_id_fkey. But why the name matters. Its automatically generated by ecto. So i think default should work

We’d need to see the schema and the migration to answer this question.

Its working fine. But throw an error if I remove name

That is because name is the fk constraint name not the column.

You could do foreign_key_constraint(:facility_id) but your key in the changeset would be facility_id not users. As far as I understand the name option is needed if the key does not match the column name as this method relies on the database.

Thanks for your answer. Can you please elaborate it a little bit with some example code.

Thanks

Your foreign key is facility_id on a table called users_facilities (I assume this is a through table with a many to many relationships). If you want to check for the facility_id you have to use that name as the key for that function.

With users as the key. users is not the name of the foreign key so the name option is required.

record
 |> Ecto.Changeset.change()
 |> Ecto.Changeset.foreign_key_constraint(:users, name: :users_facilities_facility_id_fkey,
       message: "are still associated with id"
     )


{:error,
 #Ecto.Changeset<
   action: :create,
   changes: %{
     facility_id: 1
   },
   errors: [users: {"are still associated with id", []}],
   data: #Module<>,
   valid?: false
 >}

Without the name option, the key should match the foreign key in the DB or it will throw and error.

  record
     |> Ecto.Changeset.change()
     |> Ecto.Changeset.foreign_key_constraint(:facility_id, message: "are still associated with id")


    {:error,
     #Ecto.Changeset<
       action: :create,
       changes: %{
         facility_id: 1
       },
       errors: [facility_id: {"are still associated with id", []}],
       data: #Module<>,
       valid?: false
     >}

Refence: https://hexdocs.pm/ecto/Ecto.Changeset.html#foreign_key_constraint/3

2 Likes