Ad

Undefined Method `comment_url' For #

- 1 answer

I am following a tutorial on youtube and trying to set comments on posts without page refresh. I have this setup in .js file. But in route redirect I got this error - CommentsController

class CommentsController < ApplicationController
 def create
   @article = Article.find(params[:article_id])
   @comment = @article.comments.create(params[:comment].permit(:name, :body))
   @comment.name = current_user.email
   respond_to do |format|
     if @comment.save
       format.js 
       format.html { redirect_to @comment }
       format.json { render :show, status: :created, location: @comment }
     else
     end
   end
 end

 def destroy
   @article = Article.find(params[:article_id])
   @comment = @article.comments.find(params[:id])
   @comment.destroy
   redirect_to article_path(@article)
 end
end

routes.rb

 Rails.application.routes.draw do

   get 'search/index'

   devise_for :users
   get 'welcome/index'
   get '/search', to: 'search#search'

   resources :user
   resources :articles do
     resources :comments
     member do
       put "like" => "articles#like"
       put "unlike" => "articles#unlike"
      end
    end
   resources :search, only: [:index]

   root 'welcome#index'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org             /routing.html
 end

Error -

     NoMethodError (undefined method `comment_url' for                                                           #<CommentsController:0x00007fb775ff20d8>):

     app/controllers/comments_controller.rb:10:in `block (2 levels) in create'
     app/controllers/comments_controller.rb:7:in `create'

create.js.erb file

   $('#forma2 table').append("<%= j render @comment %>")
Ad

Answer

You have nested routes: users > comments therefore you can't redirect_to @commentthis way.

Your create action would need something like:

if @comment.save
  format.js 
  format.html { redirect_to user_comments_path(current_user, @comment) }
  format.json { render :show, status: :created, location: @comment }
else
  format.html { render :new }
  format.json { render json: @comment.errors, status: :unprocessable_entity }
end

Please check your routes by issuing this at your command line: bundle exec rake routes

Also have a look to nested resources and routes on the official guides.

Ad
source: stackoverflow.com
Ad