继续得到错误"未定义的方法`post_comment_url'为#

时间:2014-11-02 00:16:21

标签: ruby-on-rails ruby

我是编程新手,现在已经学习Ruby on Rails大约六个星期了。

我试图添加"评论"我的应用中显示帖子的页面的功能(post#show)。我在/posts/show.html.erb文件中渲染了两个部分 - 一个显示评论表单(_form.html.erb),另一个显示帖子的所有评论(_comment.html.erb) )。表单渲染得很好,但是当我尝试渲染_comment.html.erb部分时,我收到以下错误:

**NoMethodError in CommentsController#create**
**undefined method `post_comment_url' for #<CommentsController:0xacfb188>**

Extracted source (around line #11):



    if @comment.save
         flash[:notice] = "Comment was created"
          redirect_to [@post, @comment]
       else 
         flash[:error] = "Comment failed to save"
       end


```app/controllers/comments_controller.rb:11:in `create'

这是posts控制器中的create方法:

    def create
     @topic = Topic.find(params[:topic_id])
     @post = current_user.posts.build(post_params)
     @post.topic = @topic
     authorize @post
      if @post.save
       flash[:notice] = "Post was saved."
        redirect_to [@topic, @post]
    else
      flash[:error] = "There was an error saving the post. Please try again."
      render :new
    end
  end

这是评论控制器中的创建方法 -

def create  
   @post =  Post.find(params[:post_id])
   @comment = current_user.comments.build(params_comment)
   @comment.post = @post
   authorize @comment

   if @comment.save
     flash[:notice] = "Comment was created"
      redirect_to [@post, @comment]
   else 
     flash[:error] = "Comment failed to save"
   end
  end

这是我的帖子/ show.html.erb文件:

<h1><%= markdown @post.title %></hi>

<div class="row">  
<%= image_tag(@post.image.thumb.url) if @post.image? %> 
  <div class= "media">
    <small>
    <%= image_tag(@post.user.avatar.tiny.url) if @post.user.avatar? %>
    submitted <%= time_ago_in_words(@post.created_at) %> ago by
    <%= @post.user.name %> 
    <p><%= @post.body %></p>
    </small>
   </div>
  <div class="col-md-4">
    <% if policy(@post).edit? %>
      <%= link_to "Edit", edit_topic_post_path(@topic, @post), class: 'btn btn-success' %> 
      <% end %> 
     <%= render partial: 'comments/form', locals: { post: @post, comment: @comment } %>
     <%= render partial: 'comments/comment', locals: { post: @post, comment: @comment } %> 
    </div>
  </div>

这是_comment.html.erb partial:

<%= form_for [post, comment] do |f| %>
  <p><%= @comments.each do |comment| %></p>
  <p><%= @comment.body %>
  <% end %> 
<% end %>

rake路线会显示以供评论:

   post_comments POST   /posts/:post_id/comments(.:format)         comments#create

错误显示我没有正确重定向(并且我尝试了几种不同的方式),但是使用rake路线显示post_comments,我不确定还有哪些重定向到。这里的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您的路线定义为post_comments(请注意复数)。因此,请将post_comment_url更改为post_comments_url