Is there an AR.delete CASCADE option?


#1

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


#2

On 11/9/05, Carl Y. removed_email_address@domain.invalid 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


#3

Carl Y. wrote:

these rows?

Thanks,

Carl

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

http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html

Regards,
Blair


#4

Thanks. In this case, things got deleted automatically when I used
destroy_all instead of delete_all.

Carl


#5

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