首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何调试“Articles#show中的NoMethodError”?

如何调试“Articles#show中的NoMethodError”?
EN

Stack Overflow用户
提问于 2019-02-15 09:37:46
回答 1查看 30关注 0票数 0

我正在尝试用Ruby on Rails制作迷你博客,并尝试在展示页面上添加评论区。

错误日志

代码语言:javascript
复制
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

代码语言:javascript
复制
<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_CONTROLER.rb

代码语言:javascript
复制
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

你能帮帮我吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-15 09:52:38

我认为自从@ @comment.comments.build has_many评论和你第一次创建@comment以来,这里的问题是空的,并且显示该错误的错误

代码语言:javascript
复制
<%= form_for([@article, @comment.comments.build]) do |f| %>

您可以更改为

代码语言:javascript
复制
<%= form_for([@article, @article.comments.build]) do |f| %>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54701575

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档