Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord: Nullify foreign key after deleting a child in self-joins

I have a self-join for my model in ActiveRecord, as follows:

class Employee < ActiveRecord::Base
  has_many :subordinates, class_name: "Employee",
                          foreign_key: "manager_id"

  belongs_to :manager, class_name: "Employee"
end 

If I delete a Manager row, I expect 'manager_id' foreign key values for all employees that were under that Manager to be set to NULL. Is this something that is handles implicitly by ActiveRecord, or is it something that needs to be defined somewhere.

like image 730
Neel Vasa Avatar asked Aug 12 '15 18:08

Neel Vasa


2 Answers

You want to add dependent: :nullify to your has_many association.

class Employee…
  has_many :subordinates, class_name: "Employee",
                          foreign_key: "manager_id",
                          dependent: :nullify
end

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

like image 112
Philip Hallstrom Avatar answered Oct 20 '22 08:10

Philip Hallstrom


Ideally you should have the trigger be set in your database and not rely on Active Record to perform updates.


If you are just creating the table, you can:

create_table :employees do |t|
  t.references :manager, foreign_key: {to_table: :employees, on_delete: :nullify}
  # ...
end

Alternatively, if the table already exists and you are just adding the reference:

add_reference :employees,
              :manager,
              foreign_key: {to_table: :employees, on_delete: :nullify}
like image 27
ndnenkov Avatar answered Oct 20 '22 09:10

ndnenkov