如何在文章#show中调试“NoMethodError”?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在文章#show中调试“NoMethodError”?相关的知识,希望对你有一定的参考价值。

我试图通过Ruby on Rails创建迷你博客,我试图在展示页面上添加评论区域。

Error log

app/views/articles/show.html.erb:23:in `_app_views_articles_show_html_erb___2446915211162750512_70356611527980'
Started GET "/articles/9" for 127.0.0.1 at 2019-02-15 10:26:34 +0900
Processing by ArticlesController#show as HTML
  Parameters: {"id"=>"9"}
  Article Load (0.6ms)  SELECT  "articles".* FROM "articles" WHERE (9) LIMIT ?  [["LIMIT", 1]]
  ↳ app/controllers/articles_controller.rb:11
  Rendering articles/show.html.erb within layouts/application
  Comment Load (0.4ms)  SELECT "comments".* FROM "comments" WHERE "comments"."article_id" = ?  [["article_id", 7]]
  ↳ app/views/articles/show.html.erb:10
  Rendered articles/show.html.erb within layouts/application (9.3ms)
Completed 500 Internal Server Error in 25ms (ActiveRecord: 2.0ms)



ActionView::Template::Error (undefined method `comments' for nil:NilClass):
    20: 
    21: <hr>
    22: <h2> コメント追加 </h2>
    23: <%= form_for([@article, @comment.comments.build]) do |f| %>
    24: <p>
    25:   <%= f.label :commenter %><br>
    26:   <%= f.text_field :commenter %>

app/views/articles/show.html.erb:23:in `_app_views_articles_show_html_erb___2446915211162750512_70356603691620'

/app/views/articles/show.html.erb

<h2> コメント追加 </h2>
<%= form_for([@article, @comment.comments.build]) do |f| %>
<p>
  <%= f.label :commenter %><br>
  <%= f.text_field :commenter %>
</p>
<p>
  <%= f.label :body %><br>
  <%= f.text_area :body %>
</p>
<p>
  <%= f.submit %>
</p>
<% end %>

我尝试使用.build而不是.new编写注释

/app/controllers/comments_controller.rb

class CommentsController < ApplicationController
  def create
    @article = Article.find_by(params[:article_id])
    @comment = @article.comments.create(comment_params)
    redirect_to article_path(@article)
  end
private
  def comment_params
    params.require(:comment).permit(:commenter, :body)
  end
end

你能帮助我吗?

答案

我认为你这里的问题@ comment.comments.build自@article has_many评论并且你第一次创建@comment是nil,并且显示错误的错误

<%= form_for([@article, @comment.comments.build]) do |f| %>

你可以换到

<%= form_for([@article, @article.comments.build]) do |f| %>

以上是关于如何在文章#show中调试“NoMethodError”?的主要内容,如果未能解决你的问题,请参考以下文章

几篇关于VisualStudio的调试工具文章

opencv如何配置修改并调试opencv源代码

配置jetty调试maven工程

Visual Studio调试之断点技巧篇

深入探讨一下如何打断点

小程序调试技术详解(基于小猴小程序)