Forum: Ruby on Rails Is there an AR.delete CASCADE option?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Eca15b2b601e7e577d38bd5210a753ac?d=identicon&s=25 carl (Guest)
on 2005-11-12 12:49
(Received via mailing list)
I'm trying to delete an AR model with an habtm association with
another table that is enforced with foreign key rule.  The query I'm
running is:

      Resume.delete_all(["found_on <= ?", date])

But the delete is failing because the rows in the other table haven't
been deleted first.  Is there an easy way in AR to cause this delete
to cascade without having to select out the IDs of all the rows that
would be affected by this delete, delete them first and then delete
these rows?

Thanks,

Carl
F48118fe74b0c7f6fd82a0ee422fa34e?d=identicon&s=25 snacktime (Guest)
on 2005-11-12 12:49
(Received via mailing list)
On 11/9/05, Carl Youngblood <carl@youngbloods.org> wrote:
> would be affected by this delete, delete them first and then delete
> these rows?
>
> Thanks,


Assuming your database supports it, I would that if you are using a
foreign
key in the database and want it to cascade, then set it that way in the
database, otherwise don't use a foreign key at all. In other words all
or
nothing is probably the best approach.

With rails I've started to avoid using foreign keys unless they are
really
needed, especially if I want the app to support all the rails supported
databases. Look at the callbacks section in the ActiveRecord
documentation.
You can define a before_delete callback to do the deletions (even though
that callback isn't documented it does exist).

after_find is another nice callback and it's not listed as a callback,
although it's referred to briefly.

Chris
27c57aaa4bda5ac8b0593659573b522f?d=identicon&s=25 blair (Guest)
on 2005-11-12 12:49
(Received via mailing list)
Carl Youngblood wrote:
> these rows?
>
> Thanks,
>
> Carl

See the :dependent and :exclusively_dependent options when you set up
the
relationships.

http://api.rubyonrails.com/classes/ActiveRecord/As...

Regards,
Blair
Eca15b2b601e7e577d38bd5210a753ac?d=identicon&s=25 carl (Guest)
on 2005-11-12 12:49
(Received via mailing list)
Thanks.  In this case, things got deleted automatically when I used
destroy_all instead of delete_all.

Carl
56f104e103af75950b63c8693e36d7db?d=identicon&s=25 Tim.Ferrell (Guest)
on 2005-11-12 12:49
(Received via mailing list)
One small wrinkle I noticed with using that is that with children that
utilize file_column the related files in the file system do not get
purged when the db records do ... this, of course, makes sense but meant
I had to make use of destroy instead...

Tim
This topic is locked and can not be replied to.