Rails dependent destroy error

家住魔仙堡 提交于 2019-12-11 15:47:18

问题


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]


回答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


来源:https://stackoverflow.com/questions/18044424/rails-dependent-destroy-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!