# Restrict Destroying Dependent Rails Associations with Error

*Published on February 19, 2025*

---


When working with associations in Rails, managing referential integrity is quite important. One not-so-common but highly useful option is&nbsp;`dependent: :restrict_with_error`, which ensures that records with dependent associations cannot be deleted without first handling those dependencies properly.

In this post, we'll explore how&nbsp;`dependent: :restrict_with_error`&nbsp;works, why it's useful, and when to use it over other&nbsp;`dependent`&nbsp;options like&nbsp;`:destroy`,&nbsp;`:nullify`, and&nbsp;`:delete_all`. I recently discovered this option while working on a new feature, and wanted to share a summary of my understanding. I hope you find it helpful as well.

Let's consider the following&nbsp;`has_many`&nbsp;association where a&nbsp;`Team`&nbsp;model has many&nbsp;`Member`&nbsp;records, and a&nbsp;`Member`&nbsp;belongs to a&nbsp;`Team`.

```ruby
class Team < ApplicationRecord
  has_many :members
end

class Member < ApplicationRecord
  belongs_to :team
end
```

Typically, with&nbsp;`has_many`&nbsp;association, you specify the&nbsp;`dependent`&nbsp;option, which controls what happens to the associated objects when the owner is destroyed. Most of the time, you'd use the&nbsp;`dependent: :destroy`&nbsp;option, which causes all the associated objects to also be destroyed, as the following test shows.

```ruby
class Team < ApplicationRecord
  has_many :members, dependent: :destroy
end

class Member < ApplicationRecord
  belongs_to :team
end

require "test_helper"

class TeamTest < ActiveSupport::TestCase
  def setup
    @team = Team.create(name: "Engineering Team")
  end

  test "deleting team deletes associated members" do
    member_one = Member.create(name: "John Doe", team: @team)
    member_two = Member.create(name: "Jane Doe", team: @team)

    assert_difference "Member.count", -2 do
      @team.destroy
    end
  end
end
```

However, there are some times when you don't want to allow deletion of the parent records when there are one or more associated records referencing it. Allowing deletion can lead to unintended data inconsistencies.

For example, let's imagine that for some business constraints, we don't want to allow any members to exist without a team. Hence we'd like to prevent deletion of a team when it has one or more members. Users can delete a team only after all the members of that team have been destroyed.

Rails provides the&nbsp;`dependent: :restrict_with_error`&nbsp;option to handle this exact use-case. Let's give it a try.

```ruby
class Team < ApplicationRecord
  has_many :members, dependent: :restrict_with_error
end
```

With this configuration, attempting to delete a&nbsp;`Team`&nbsp;that still has associated&nbsp;`Member`&nbsp;records will:

- **Prevent the deletion**&nbsp;of the team.
- **Add an error**&nbsp;to the team model.
- **Return**&nbsp;**`false`**&nbsp;from the&nbsp;`destroy`&nbsp;method.
- **Keep the database record intact**&nbsp;to maintain referential integrity.

This behavior ensures that historical data remains valid and prevents accidental data loss. The following test that shows this behavior.

```ruby
require "test_helper"

class TeamTest < ActiveSupport::TestCase
  def setup
    @team = Team.create(name: "Engineering Team")
  end

  test "cannot delete team with members" do
    member_one = Member.create(name: "John Doe", team: @team)
    member_two = Member.create(name: "Jane Doe", team: @team)

    assert_not @team.destroy
    assert_equal 2, Member.count
    assert_includes @team.errors.full_messages, "Cannot delete record because dependent members exist"
  end

  test "can delete team without members" do
    assert @team.destroy
    assert_equal 0, Member.count
  end
end
```

### How Does It Differ from Other Options?

ActiveRecord provides multiple&nbsp;`dependent`&nbsp;options, each with its own implications:

`:destroy` : eletes associated records and triggers callbacks.

`:delete_all` : Deletes associated records directly in SQL (bypasses callbacks).

`:nullify` : Sets foreign keys to&nbsp;`NULL`&nbsp;instead of deleting records.

`:restrict_with_error` : Prevents deletion if associated records exist and adds an error.

When no option is given, the default behavior is to do nothing with the associated records when destroying a record.

Let's compare alternative approaches and why they wouldn't work as well in this scenario:

- **`dependent: :destroy`**&nbsp;→ Would delete historical&nbsp;`Member`&nbsp;records, losing valuable audit data.
- **`dependent: :nullify`**&nbsp;→ Would leave&nbsp;`Member`&nbsp;records without a&nbsp;`Team`, making it unclear why the members were created.
- **`dependent: :delete_all`**&nbsp;→ Would remove records in bulk without callbacks, potentially breaking data integrity.

Hence in this case the&nbsp;`restrict_with_error`&nbsp;option makes sense.

> 💡 Note: Rails also provides a&nbsp;`:restrict_with_exception`&nbsp;option which causes an&nbsp;`ActiveRecord::DeleteRestrictionError`&nbsp;exception to be raised if there are any associated records. However, I prefer&nbsp;`restrict_with_error`&nbsp;since it adds an error on the model.

## Why and When to Use It?

- **To Ensure Data Integrity:**&nbsp;A&nbsp;`Project`&nbsp;may be referenced by multiple&nbsp;`Task`&nbsp;records. Deleting the project would leave historical records without context, making data incomplete or meaningless.
- **To Provide User Feedback:**&nbsp;When an attempt is made to delete a record with associated entries, Rails adds a validation error, which can be displayed to the user. This prevents silent failures and informs the user about necessary actions.
- **To Maintain an Audit Trail**: For business applications that track project management, task assignments, or work logs, retaining historical references is critical for audits and analytics.

**What's the takeaway?**&nbsp;When designing your Rails models, consider the implications of different&nbsp;`dependent`&nbsp;options and choose the one that best fits your application's needs. In cases where data consistency is important,&nbsp;`:restrict_with_error`&nbsp;is quite often the best choice.

