0

I have a Rails Movie app. With, obviously, a movie table. A movie has_many :comments, :dependent => :destroy and a comment belongs_to :movie. A comment also belongs_to :user so when a new User comments on a movie, that comment will display on their users#show page.

If a User Comments on a Movie, the comment will display on their page. I can also go to localhost:3000/comments/:id to see that comment's show page

Now my problem is this:

If I then destroy or delete that movie with that comment, the comment doesnt actually get deleted. I can still go to localhost:3000/comments/:id, and if i go to the users/:id/reviews (where the user's comments are displayed) I get an error because that comment is still being displayed and still belongs to a movie. So i get an error of this sort Unable to find Movie with id = 58

Is there a way in the Movies_controller.rb destroy action to say when the movie is deleted, also delete all comments with movie_id => params[:id]

PMP
  • 231
  • 6
  • 25
  • `:dependent` should be a symbol in this line: `has_many :comments, :dependent => :destroy`. If this is a typo in your actual code, fix and and see if this resolves the issue. This thread might help you with your question about the `MoviesController#destroy` action: http://stackoverflow.com/questions/3547616/dependent-destroy-isnt-calling-the-destroy-method-before-the-deletion – Powers Aug 04 '13 at 15:33
  • My code isnt with me right now but I do think that in my model the colon is already there, so it was just a problem with the question and not the code. Edited it. – PMP Aug 04 '13 at 15:44

1 Answers1

1

There is another way to delete comments of a movie:

def destroy
 @movie = Movie.find(params[:id])
 @movie.comments.delete_all
 @movie.destroy
end
rmagnum2002
  • 11,341
  • 8
  • 49
  • 86
  • Ok so this works BUT it signs the user out. So it by destroying the movie and the comment you're also destroying the user session – PMP Aug 04 '13 at 17:11
  • this problem comes not from my code, in fact, the problem is somewhere else and I suspect this is why your dependent: :destroy didn't worked. Put your logs for the destroy movie action. – rmagnum2002 Aug 04 '13 at 17:25
  • I wasnt implying that it was because of your code, but just that it triggers it. https://gist.github.com/mpcoding/b8c95a7103916baba3dd – PMP Aug 04 '13 at 17:31
  • show your application.html.erb, or check if you have `<%= csrf_meta_tag %>` in it. – rmagnum2002 Aug 04 '13 at 17:44
  • there is an warning in your logs `WARNING: Can't verify CSRF token authenticity` and I guess this might be related to this. – rmagnum2002 Aug 04 '13 at 17:45
  • either way, logs clearly shows that comments are deleted and movie too.. could be some filter that you used wrong for authentication, could a wrong redirect that you do on calling destroy, etc... hard to guess, but after you fix this you can use `dependent: :destroy` again I think. – rmagnum2002 Aug 04 '13 at 17:49