Hello, when I want to delete a category I have just deleted the category always with on_delete: :delete_all and because I used that all of my post were deleted, but this time I need to show an error massage to my client when they need to delete some category they should delete all post of the category first and next can delete category.
|> foreign_key_constraint(:category_id, message: "this category has some post and you can't delete it")
but it doesn’t work and shows me an error:
** (exit) an exception was raised:
** (Ecto.ConstraintError) constraint error when attempting to delete struct:
* blog_posts_category_id_fkey (foreign_key_constraint)
If you would like to stop this constraint violation from raising an
exception and instead add it as an error to your changeset, please
call `foreign_key_constraint/3` on your changeset with the constraint
`:name` as an option.
I just want to show a custom error I need how can do it ?
Can you please tell us how you try to delete the record?
Also it seems, as if you also need to provide name: :blog_posts_category_id_fkey as an option to the constraint (or does the name need to be a string?).
No changeset involved. So nothing you add, remove or change in your changeset would change anything. You need to pass category through the changeset that has the constraint as far as I understand the changeset stuff.
I have no clue what you mean by this, but on a first glance it reads like you want to check whether or not posts exist before deleting. This is subject to a race. You should strictly avoid this.
Use the constraint.
PS: As far as I know, calling into Repo directly from the controller is considered bad practice, one should only use the appropriate context modules.