Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set up Cascade deleting in Rails?

I know this is probably on the Internet somewhere but I can't find the answer here on Stackoverflow so I thought I may boost up the knowledge base here a little.

I'm a newbie to Ruby and Rails but my company is getting pretty invested in it so I'm trying to get to know it in a little more detail.

It's been difficult for me to change my mindset to designing an application from the "model" rather the from the database, so I'm trying to figure out how would do all of the design work that I have classically done in the Database in the Rails model instead.

So the most recent task that I have given myself is to figure out how to configure a Rails database model to do cascading deletes? Is there an easy way of doing this? Or would I have to go into the MySql and set this up?

like image 243
matt_dev Avatar asked Dec 01 '08 16:12

matt_dev


People also ask

Is it good to use on delete cascade?

Yes, the use of ON DELETE CASCADE is fine, but only when the dependent rows are really a logical extension of the row being deleted. For example, it's OK for DELETE ORDERS to delete the associated ORDER_LINES because clearly, you want to delete this order, which consists of a header and some lines.

Is cascade a delete rule?

A foreign key with cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete in SQL Server.

Is on delete cascade a trigger?

Sadly cascaded deletes do not activate triggers in MySQL.


1 Answers

you can also set the :dependent option to :delete_all. :delete_all will issue a single SQL statement to delete all child records. because of this using :delete_all may give you better performance.

has_many :memberships, dependent: :delete_all 
like image 196
Mike Breen Avatar answered Sep 17 '22 12:09

Mike Breen