sharkmyster
I’m using an adjacency list to store a hierarchy of categories. There can be many root categories each with many children/descendants.
defmodule WordSolverDal.Categories.Category do
use Ecto.Schema
import Ecto.Changeset
use Arbor.Tree,
foreign_key: :parent_id,
foreign_key_type: :integer
schema "categories" do
field(:name, :string)
field(:parent_id, :integer)
many_to_many(:answers, WordSolverDal.Answers.Answer, join_through: "answers_categories")
timestamps()
end
@required [:name]
@optional [:parent_id]
def changeset(category, attrs) do
category
|> cast(attrs, @required ++ @optional)
|> validate_required(@required)
|> validate_length(:name, min: 3)
|> unique_constraint(:name, name: :unique_categories_name_parent_id_null)
|> unique_constraint(:name, name: :unique_categories_name_parent_id)
end
end
The db throws a constraint error if a user tries to delete a record that has children due to the foreign key constraint on :parent_id.
constraint error when attempting to delete struct:
* "categories_parent_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.
This error gives advice on how to handle the error without raising an exception but I don’t see how this could work. As I understand it, foreign_key_constraint/3 is typically used for insert/update change sets.
How can I attempt a delete and not raise an exception as described? Or should I just rescue the error?
Trending in Questions
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
Hello,
I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
Hi everyone,
I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding.
I sta...
New
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
So my question is quite simple and i have found no conclusive answer on forum, google or AI.
Should we use :erlang.float for Integer to ...
New
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
Other Trending Topics
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hi there! We created Gust: A task orchestrator inspired by Airflow.
For those who have never heard about Aiflow, it’s a Python-based wor...
New
Hi everyone!
The first release candidate for the Expert language server project is now available!
We’ve published a press release detai...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixirconf-us
- #ai
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #hex
- #security











Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
kokolegorille
Can You show your categories migrations?
There should be something like this…
sharkmyster
ken-kost
Have you thought about soft delete? I feel this would solve your problem and give you a bonus to restore deleted categories.
sharkmyster
I want to inform the user that the category has sub-categories and should not be deleted.
kokolegorille
Maybe no_assoc_constaint
sbuttgereit
A Changeset is just a validation mechanism and there’s nothing inherent in them that prevents their use in deletion. I do agree that most people focus on insert and update when discussing Changesets, but validation is validation and there can be reasons to validate delete operations including your scenario. You’ll see that
Ecto.Repo.delete/2can take a Changeset: Ecto.Repo — Ecto v3.14.0.Personally, I like the idea of Changesets and handling validation prior to attempting operations on the database, even for deletes… though I’d likely have delete-specific Changeset checks. It might be overly defensive on this, because I also absolutely believe that it’s not a substitute for correct constraints in the database, too, but by validating in the application I feel like I’m more in control. I also like raised exceptions to be logged and not depending on them for my logic means that I can be very consistent about that without thinking too much about it.
ibarch
As far as I know, this is the idiomatic solution. Another option is to manually catch the exception within a
try/rescueblock, but this method is rather ugly so I’d recommend to use it as a last resort.dimitarvp
no_assoc_constraintwill indeed give you niceChangeseterror that you can directly work with in forms.But if for one reason or another that’s not an option for you then you could always take the direct route:
sbuttgereit
But isn’t this in effect just
Ecto.Changeset.foreign_key_constraint/3except performing the foreign key check fully manually in advance?My understanding is that database constraint validations (unique, foreign key, etc.) in Changesets aren’t checked in advance and rely on database error reporting to return a Changeset error post-execution attempt. Using a Changeset here with a
foreign_key_constraint/3check allows the database constraint to abort the database transaction on query with the appropriate error where Ecto picks it up and report it as a Changeset error. So while what your saying will work, I’m not sure I see the advantage to handling that way rather than submitting a Changeset… two queries vs. one.sharkmyster
So, using a changeset and
no_assoc_constraintdoesn’t work for me.I get the following error: