Rails cannot delete or update the parent row: foreign key constraint not implemented

I want to delete something from my database. The value refers to some other tables.

Error:

Mysql2::Error: Cannot delete or update a parent row: a foreign key constraint fails

How can I resolve this correctly?

If I add some restrictions, for example, for the delete cascade, other values ​​will not be deleted correctly?

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
+4
source share
4 answers

If you created foreign keys with ActiveRecord::Migration, it will use it ON DELETE RESTRICTby default (i.e. the parent record will NOT be deleted if there are records in the link tables).

, 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
+3

, Model.rb

has_many :model, :dependent => :delete_all 

, .

, , Post.rb Comment.rb

post.rb

has_many :Comments, :dependent => :delete_all

, , .

,

+2

delete, :

before_destroy after_destroy any: , #destroy.

, destroy , :

def delete
   @vid = Movie.find params[:id]
   @vid.destroy
   redirect_to :action => :add
end

Comment Movie, , , , , .

+2

?

, . , .

, ActsAsParanoid ?

+1

All Articles