Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails cannot delete or update a parent row: a foreign key constraint fails

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
like image 671
Felix Avatar asked May 04 '16 11:05

Felix


People also ask

How do I delete a foreign key constraint?

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.

How do I fix SQL error 1452?

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.


Video Answer


1 Answers

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
like image 74
Rael Gugelmin Cunha Avatar answered Sep 17 '22 14:09

Rael Gugelmin Cunha