Ruby on Rails错误:未定义的方法`comments_path'

时间:2014-12-17 20:45:34

标签: ruby-on-rails

我正在创建一个用户可以对帖子发表评论的应用。但是,我在尝试展示帖子时遇到错误:ArgumentError in PostsController#show First argument in form cannot contain nil or be empty

在我尝试render 'shared/comment_form'

的路线上失败了

以下是我的帖子/ 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>

和我的 posts_controller.rb

class PostsController&lt; ApplicationController的      before_action:logged_in_user,仅限:[: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

这是我的 shared / _comment_form.html.erb 部分:

<%= 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 %>

我的 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

暂且不说:我知道在Comment.new中使用form_for并不习惯 - 我也遇到了问题,但我想一次解决一个问题(除非他们以某种方式参与其中)

1 个答案:

答案 0 :(得分:2)

我怀疑你的config / routes.rb文件中没有条目用于评论,即:

resources :comments