rails/rails — Issue #3881: Get association on ActiveRecord::DeleteRestrictionError exception
Author: sobrinho
Created: 2011-12-06 20:13:02+00:00
State: open

Hello,

I have the following model:

``` ruby
class Profile < ActiveRecord::Base
has_many :users, :dependent => :restrict
end
```

Controller raises:

```
ActiveRecord::DeleteRestrictionError in ProfilesController#destroy

Cannot delete record because of dependent users
```

But I can't handle this exception gracefully on controller because I don't know the association name.

I need to do something like that:

``` ruby
def destroy
...
rescue ActiveRecord::DeleteRestrictionError => e
association = e.message.match(/of dependent ([a-z_]+)/)[1].to_sym
reflection = Profile.reflect_on_association(association)

...
end
```

I need that because none object can be destroyed on my system if have dependents and I need to tell user which dependency is blocking the destroy (i18n is required).

I'm thinking in these methods:

``` ruby
e.association_name
# => :users

e.association_reflection
# => #
```

I don't know which is the best option but we need some way to handle this exception message :)

Sometime ago, cancan handled the unauthorized access exception message using i18n but this is complex here because we need to use locale for object, association name and the message itself.

Some examples:

```
Categoria não pode ser apagada porque existem posts associados.
Categoria não pode ser apagada porque existem sub-categorias associadas.
```

```
Post não pode ser apagado porque existem comentários associados.
Post não pode ser apagado porque existem tags associadas.
```

Note we have four situations for brazilian locale:

```
%{model_name} não pode ser %{male or female destroyed} porque existem %{association_name} {male or female dependent}.
```

The first issue is a active record exception problem but second maybe.