我是新手編程人員,並且現在已經學習了Ruby on Rails大約六週。當試圖呈現評論時,爲#<CommentsController「繼續收到錯誤」undefined method`post_comment_url「
我想添加「評論」功能到我的應用程序顯示一個帖子(帖子#顯示)的頁面。我在/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控制器的創建方法:
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部分:
<%= form_for [post, comment] do |f| %>
<p><%= @comments.each do |comment| %></p>
<p><%= @comment.body %>
<% end %>
<% end %>
耙路線顯示了這個意見:
post_comments POST /posts/:post_id/comments(.:format) comments#create
錯誤表明我不是正確的重定向(我嘗試了幾種不同的方法),但是使用顯示post_comments的rake路由,我不確定還有什麼要重定向到的。任何幫助在這裏將不勝感激。