Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Option for Cascade Delete for References or On Delete

In Rails 4.2, when creating a table or adding a reference via references or add_reference how do you specify that the foreign key should cascade on delete.

Command to generate scaffold:

rails g scaffold Child parent:references name:string 

Resulting migration:

create_table :childs do |t|   t.references :parent, index: true, foreign_key: true   t.string :name    t.timestamps null: false end 
like image 842
WiredIn Avatar asked May 10 '15 18:05

WiredIn


People also ask

Should I use on delete cascade?

Should we 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.

Which cascade delete option is used for?

DELETE CASCADE: When we create a foreign key using this option, it deletes the referencing rows in the child table when the referenced row is deleted in the parent table which has a primary key.

What is the purpose on delete cascade delete?

ON DELETE CASCADE clause in MySQL is used to automatically remove the matching records from the child table when we delete the rows from the parent table. It is a kind of referential action related to the foreign key.


1 Answers

This should work

create_table :childs do |t|   t.references :parent, index: true, foreign_key: {on_delete: :cascade}   t.string :name    t.timestamps null: false end 

According to ActiveRecord::ConnectionAdapters::TableDefinition#references, if a hash is specified on the foreign_key option, it is directly passed down into the foreign_key method.

source:

foreign_key(col.to_s.pluralize, foreign_key_options.is_a?(Hash) ? foreign_key_options : {}) if foreign_key_options 
like image 115
Kern Cheh Avatar answered Sep 27 '22 17:09

Kern Cheh