Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ecto.Schema differences between nilify_all, nothing, and delete_all?

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?

like image 411
Iggy Avatar asked Mar 05 '23 03:03

Iggy


1 Answers

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.

like image 138
Navin Peiris Avatar answered Apr 06 '23 06:04

Navin Peiris