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.
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
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With