I want to delete something from my database.
The value references some other tables.
Mysql2::Error: Cannot delete or update a parent row: a foreign key constraint fails
@vid = Movie.find params[:id]
redirect_to :action => :add
class Movie < ActiveRecord::Base
has_many :comments, :dependent => :destroy
mount_uploader :video, MovieUploader
class Comment < ActiveRecord::Base
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] @vid.destroy redirect_to :action => :add end
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.