Select Page

Deleting Associated Records in Ruby on Rails

by | Sep 2, 2023 | Active Record | 0 comments

Ruby on Rails provides a lot of powerful tools for working with associations between models. One common use case is to delete associated records when a parent record is destroyed. In this blog post, we’ll explore how to delete a guest record when a reservation record is destroyed, but only if the guest has no other reservations.

First, let’s take a look at the two models involved. We have a Guest model, which has many Reservations, and a Reservation model, which belongs to a Guest.

class Guest < ApplicationRecord
  has_many :reservations, dependent: :destroy
end

class Reservation < ApplicationRecord
  belongs_to :guest
end

By specifying dependent: :destroy in the has_many association, we tell Rails to destroy all associated reservation records when a guest is destroyed. However, we also want to delete the associated guest record when a reservation is destroyed, but only if the guest has no other reservations.

To achieve this, we can add a before_destroy callback to the Reservation model that checks whether the guest has any other reservations. If the guest has only one reservation (the one being destroyed), we can safely delete the guest record as well. Here’s what the code looks like:

class Reservation < ApplicationRecord
  belongs_to :guest
  
  before_destroy :delete_guest_if_last_reservation

  private

  def delete_guest_if_last_reservation
    if guest.reservations.count == 1
      guest.destroy
    end
  end
end

In this code, the before_destroy callback calls the delete_guest_if_last_reservation method, which checks whether the guest has any other reservations. If the guest has only one reservation (the one being destroyed), it calls guest.destroy to delete the guest record as well.

Note that we’ve made the delete_guest_if_last_reservation method private, since it’s only used internally within the Reservation model. This is a good practice to follow for helper methods that are not intended to be called externally.

That’s all there is to it! With this code in place, you can safely delete reservation records and associated guest records, knowing that guests with other reservations will not be accidentally deleted.

In conclusion, deleting associated records in Ruby on Rails is easy and powerful, but it’s important to be careful to avoid accidentally deleting important data. By adding a before_destroy callback to the Reservation model, we can delete associated guest records when a reservation is destroyed, but only if the guest has no other reservations.