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.
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.
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
>}