Ecto.Schema differences between nilify_all, nothing, and delete_all?
Asked Answered
G

1

7

I am defining a schema for my user and role models in Phoenix app. Role has_many users and user belongs_to a role. It seems like there are 3 different on_delete: options: nilify_all, nothing(default), and delete_all.

When I look at Ecto.Schema page, I don't really find definition of what each does.

What is the difference between nilify_all, nothing, and delete_all - when should I use each?

Gainsborough answered 31/10, 2018 at 22:27 Comment(1)
Just wanted to say that the docs don't recommend using this option. Instead, they recommend setting it on the DB (migration) directly. hexdocs.pm/ecto/Ecto.Schema.html#has_many/3Evidence
A
12

The on_delete option specifies what should happen to the associated records when a record is deleted.

Considering your example where a role has many users:

  • delete_all: Deletes the associated records when the parent record is deleted. For example in your case deleting a role will delete all the users that are associated with that role.

  • nilify_all: This sets the key in the associated table that points to the parent record to nil when the parent record is deleted. For example when a role is deleted, this will set the role_id in the users table to nil of those users that belonged to that role.

  • nothing: This would not do anything to the associated records when the parent record is deleted. This will however throw an error if the associated table has a foreign key constraint back to the parent table.

Ap answered 1/11, 2018 at 8:50 Comment(2)
is there a way to :protect the role from deleted? let's say accidentally deleted roleGarda
@Loonb In this case you would use the :restrict option. This will stop a role being deleted if it's in use by users, however it won't stop a role that is unused from being deleted.Runoff

© 2022 - 2024 — McMap. All rights reserved.