I want to delete something from my database. The value references some other tables.
Error is:
Mysql2::Error: Cannot delete or update a parent row: a foreign key constraint fails
How can I resolve this properly?
If I add some constraints like on delete cascade the other values won't be deleted right?
Edit:
def delete
@vid = Movie.find params[:id]
@vid.delete
redirect_to :action => :add
end
Update Models
movie.rb
class Movie < ActiveRecord::Base
has_many :comments, :dependent => :destroy
has_many :ratings
belongs_to :channel
has_and_belongs_to_many :tags
has_and_belongs_to_many :categories
mount_uploader :video, MovieUploader
comment.rb
class Comment < ActiveRecord::Base
belongs_to :movie
belongs_to :user
belongs_to :rating
To delete a foreign key constraint In Object Explorer, expand the table with the constraint and then expand Keys. Right-click the constraint and then click Delete. In the Delete Object dialog box, click OK.
There are two ways you can fix the ERROR 1452 in your MySQL database server: You add the value into the referenced table. You disable the FOREIGN_KEY_CHECKS in your server.
If you've created the foreign keys using ActiveRecord::Migration
, it'll use ON DELETE RESTRICT
by default (i.e, the opposite of what you want: row entry will be NOT deleted if there are entries with references from other tables).
You need to change your migration to use ON DELETE CASCADE
:
class CreateChild < ActiveRecord::Migration
def change
create_table :child do |t|
t.references :parent, foreign_key: {on_delete: :cascade}
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With