Neel Vasa
Neel Vasa

Reputation: 179

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.

Upvotes: 9

Views: 8024

Answers (2)

ndnenkov
ndnenkov

Reputation: 36101

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}

Upvotes: 4

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

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

Upvotes: 12

Related Questions