Felix Felix - 2 years ago 140
SQL Question

Rails delete something from databse but references 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?


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

Update Models


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


class Comment < ActiveRecord::Base
belongs_to :movie
belongs_to :user
belongs_to :rating

Answer Source

You are using delete, from the documentation:

To enforce the object's before_destroy and after_destroy callbacks or any :dependent association options, use #destroy.

So you need to use destroy instead so that the proper callback from rails to remove dependent records is executed:

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

Because your Comment records depend on the Movie record that you are trying to delete, hence, since rails is just trying to remove the movie before the comments the database engine complains if there is a foreign key from the comment table to the movie table.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download