Reputation: 3
I have a form to submit comments on posts.
After submitting comments, the user should be redirected to the post.
I am getting the following error when I hit the "submit" button:
NameError in CommentsController#create undefined local variable or method `post' for CommentsController...
The error points to the following line in my comments controller:
redirect_to post_path(@post)
Here's my comments_controller.rb
:
class CommentsController < ApplicationController
before_action :authenticate_user!
def create
@topic = Topic.find(params[:topic_id])
@post = @topic.posts.find(params[:post_id])
@comment = Comment.new(comment_params)
@comment.post = @post
redirect_to post_path(@post)
end
private
def comment_params
params.require(:comment).permit(:title, :body)
end
end
And here's my route file:
Rclone::Application.routes.draw do
get "comments/create"
devise_for :users
resources :users, only: [:update]
resources :topics do
resources :posts, except: [:index] do
resources :comments, only: [:create]
end
end
get '/posts/:id/comments', to: 'posts#show'
get 'about' => 'welcome#about'
root to: 'welcome#index'
end
What am I doing wrong on the routes file?
Upvotes: 0
Views: 100
Reputation: 386
Comment.new
will not presist or create the post. You need to do @comment.save
. Also use pry
and pry-nav
gem to debug such errors. pry
will halt the execution of you program where it finds binding.pry
. From that point onwards you can execute your program line by line. Just insert binding.pry
one line before where you want to halt execution.
example
def create
binding.pry
@topic = Topic.find(params[:topic_id])
Check you params hash and you will find your bug. My guess is you are going wrong with topic_id
or post_id
Links:
http://pryrepl.org/
https://github.com/pry/pry
Upvotes: 1