H K
H K

Reputation: 1275

Ruby on Rails error: undefined method `comments_path'

I am creating an app in which users can comment on posts. However, I am getting an error when trying to show posts: ArgumentError in PostsController#show First argument in form cannot contain nil or be empty

It's failing on the line where I try to render 'shared/comment_form'

Here is my posts/show.html.erb:

<% provide(:title, @post.title) %>
  <div class="post-details">
    <div class="post-title">@post.title</div>
    <div class="post-url">@post.url</div>
    <div class="post-content">@post.content</div>
    <%= render 'shared/comment_form' if logged_in? %>
    <% if @post.comments.any?  %>
      <h3>Comments</h3>
      <ol class="comments">
        <%= render @comments  %>
      </ol>
    <% end  %>
  </div>

and my posts_controller.rb:

class PostsController < ApplicationController before_action :logged_in_user, only: [:create, :destroy]

 def create
   @post = current_user.posts.build(post_params)
   if @post.save
     flash[:success] = "Post created!"
     redirect_to root_url
   else
     @feed_items = []
     render 'static_pages/home'
   end
 end

 def show
   @post = Post.find(params[:id])
 end

 private

   def post_params
     params.require(:post).permit(:title, :url)
   end
end

And here's my shared/_comment_form.html.erb partial:

<%= form_for(Comment.new) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
   <div class="field">
      <%= f.text_area :content, placeholder: "Compose new comment..." %>
</div>
<%= f.submit "Post", class: "btn btn-primary" %>
<% end %>

And my comments_controller.rb:

class CommentsController < ApplicationController

  before_action :logged_in_user, only: [:create, :destroy]

def create
  @comment = current_user.comments.build(comment_params)
  if @comment.save
    flash[:success] = "Comment created!"
    redirect_to request.referrer || root_url
  else
    render 'new'
  end
end

def new
  @comment = Comment.new
end

def destroy
  @comment.destroy
  flash[:success] = "Comment deleted"
  redirect_to request.referrer || root_url
end

private

  def comment_params
    params.require(:comment).permit(:content)
  end
end

An aside: I know its not customary to use Comment.new in my form_for -- I am also having an issue with that, but I'd like to solve one issue at a time (unless they're somehow involved)

Upvotes: 0

Views: 451

Answers (1)

keyzee
keyzee

Reputation: 461

I suspect that you don't have an entry in your config/routes.rb file for comments, i.e:

resources :comments

Upvotes: 2

Related Questions