Cannot redirect to Nil in CommentsController#destroy (Polymorphic association)

associations, polymorphic-associations, ruby-on-rails, ruby-on-rails-3

Solution

Figured out the solution. Will post solution in code above.

def destroy
  @comment = Comment.find(params[:id])
  @commentable = @comment.commentable
  if @comment.destroy
    redirect_to @commentable
  end
end

Problem

I am trying to write my delete method in my comment controller. My comment model has polymorphic associations with other models but in this case, we'll just focus on trips. In other words, @trip = @commentable. The comment gets deleted just fine, but I keep getting the error `ActionController::ActionControllerError in CommentsController#destroy: Cannot redirect to nil!` when I redirect_to @commentable which would be the trip that the comment belonged to. I also redirected to @commentable in my create action (comment controller) and that works just fine when the user creates a new comment. Any tips? view (trips/show.html.erb) ``` <% if !@commentable.comments.empty? %> <% @commentable.comments.each do |comment| %> <!-- Content --> <%= link_to comment, :method => :delete do %> delete <% end %> <% end %> <% end %> ``` comment form that works for create action ``` <%= form_for [@commentable, Comment.new] do |f| %> <%= f.text_area :content %> <div id="comment_submit_button"><%= f.submit "Comment" %></div> <% end %> ``` trips_controller.rb ``` def show @trip = @commentable = Trip.find(params[:id]) @comments = Comment.all end ``` comments_controller.rb ``` def create @commentable = find_commentable @comment = @commentable.comments.build(params[:comment]) @comment.user_id = current_user.id if @comment.save redirect_to @commentable end end def destroy # @commentable = find_commentable this line was wrong @comment = Comment.find(params[:id]) @commentable = @comment.commentable #this line fixed it if @comment.destroy redirect_to @commentable end end def find_commentable params.each do |name, value| if name =~ /(.+)_id$/ return $1.classify.constantize.find(value) end end nil end ```

Original source