2

I have a database of movies and their associated genres.

class Genre < ActiveRecord::Base
  has_many :movie_genres
  has_many :movies, through: :movie_genres, dependent: delete_all
  before_destroy :delete_movie

  private

  def delete_movie
    self.movies.delete_all
  end

end

class Movie < ActiveRecord::Base
  has_many :movie_genres
  has_many :genres, through: :movie_genres
end

My aim is that when a genre gets deletes - all of its movies also get deleted, regardless of if that movie has another genre or not. I've tried attaching dependent: :destroy to the Genre model however only the join table records get deleted. I've also tried using the before_destroy callback to delete the movies prior to deleting the genre however that didn't seem to work either.

mbillard
  • 38,386
  • 18
  • 74
  • 98
Carl Wright
  • 55
  • 2
  • 6
  • What do you mean with "only the join table records get deleted?" – Meier Jan 18 '15 at 00:19
  • what exactly happens when you use delete_movie, in which way does it not work? Is the method called? Does it generates SQL? – Meier Jan 18 '15 at 00:23

2 Answers2

0

Try :destroy_all. destroy_all will remove this and all associated objects. For large data, this can be slow though. Also See: delete_all vs destroy_all?

Community
  • 1
  • 1
Wasik
  • 35
  • 1
  • 5
0

I believe you just need to select the records where the column is applicable and then call destroy_all on them. Am I missing something?

Movie.where(movie_genre: @movie.movie_genre).destroy_all
JackHasaKeyboard
  • 1,599
  • 1
  • 16
  • 29