How to restrict deletion of ActiveRecord objects if there de


#1

Hi guys,

Trying to find some way to restrict deletion of ActiveRecord objects
if there dependent records.

I’m thinking of using before_destroy for it, but don’t know how to
“cancel” deletion in my code in before_destroy “decides” that deletion
should be restricted.

Thank you in advance.


Regards
Yuriy Padlyak


#2

gneeot wrote:

I’m thinking of using before_destroy for it, but don’t know how to
“cancel” deletion in my code in before_destroy “decides” that deletion
should be restricted.

According to the Rails doc, all you need to do is return false from your
before_destroy method. Here’s the relevant section:

== Cancelling callbacks

If a before_* callback returns false, all the later callbacks and

the associated action are cancelled. If an after_* callback returns

false, all the later callbacks are cancelled. Callbacks are

generally run in the order they are defined, with the exception of
callbacks

defined as methods on the model, which are called last.

Hope this helps,

Adam


#3

Hi Yuryi,

Trying to find some way to restrict deletion of ActiveRecord objects
if there dependent records.

I’m thinking of using before_destroy for it, but don’t know how to
“cancel” deletion in my code in before_destroy “decides” that deletion
should be restricted.

I’m pretty sure that if a “before_” filter returns false, the whole
action
is canceled. Check the class docs at api.rubyonrails.org to be sure.

HTH,
Bill


#4

it works great, thank you.


#5

thanks, will try it.