Search code examples
ruby-on-railsruby-on-rails-4has-manybelongs-to

Rails: HT switch Parent of Child objects when Deleting Parent?


I'm building a small app with Rails 4.2.6. Suppose I have the following classes:

class Caseworker < ActiveRecord::Base
  has_many :cases
end

class Case < ActiveRecord::Base
  belongs_to :caseworkers
end

... with views to create, view, update, and destroy them each. I then create multiple Caseworkers and assign multiple Cases to them.

Currently, if I attempt to delete a Caseworker, I'll get an error:

Mysql2::Error: Cannot delete or update a parent row: a foreign key constraint fails

No problem, that's to be expected.

In some CMSes, though, if a user attempts to destroy an object with such dependencies, you can present them with the option to assign the objects to another parent, or destroy them. Is there a standard way, in Rails, to offer this functionality? Otherwise, it seems like I will need to put a before_destroy clause in the Caseworker controller... is this true? I'm not afraid to write such a method if need be, but I'd rather not reinvent this wheel if it's there for me to use somewhere.


Solution

  • You can add one of dependent: :destroy or dependent: :nullify to the has_many statement, depending on whether you want the children deleted or to have their foreign key field nulled.

    For example, to delete the Cases belonging to a Caseworker being deleted you could use:

    class Caseworker < ActiveRecord::Base
      has_many :cases, dependent: :destroy
    end
    

    To my knowledge Rails has no way to reassign children to a different parent - you'd have to write code to do that yourself.