Ruby on rails - 无法创建评论。 NoMethodError

时间:2017-11-14 20:29:58

标签: ruby-on-rails ruby comments ruby-on-rails-5

我正在创建我的第一个RoR应用程序 - 一个论坛。我试着在论坛上添加评论,但是我收到了一些错误。我用谷歌搜索过类似的问题,但似乎没有解决我的问题。这是我的代码:

评论控制器:

class CommentsController < ApplicationController
  def create
    @forum = Forum.find(params[:forum_id])

    if !@forum.nil?
        puts "Forum object is not nil"
    end

    @comment = @forum.comment.create(comment_params)

    redirect_to forum_path
  end

  private

  def comment_params
    params.require(:comment).permit(:body)
  end
end

论坛控制器是自动生成的,我还没有改变。(使用rails生成脚手架论坛生成,如果你还想看到它,请告诉我)

class Comment < ApplicationRecord
  belongs_to :forum
end

class Forum < ApplicationRecord
  has_many :comments
  validates :title, presence: true,
  length: {maximum: 50}
  validates :body, presence: true
end

以下是论坛页面show.html.erb 部分的表单

<h2>Comments</h2>

<% @forum.comments.each do |comment| %>
<p>
    <%= comment.body %>
</p>

<% end %>

<h2>Add a comment</h2>

<%= form_for([@forum, @forum.comments.build]) do |f| %>
<p>
    <%= f.label :body %><br/>
    <%= f.text_area :body %>
</p>
<p>
    <%= f.submit %>
</p>
<% end %>

这是rails的错误:

undefined method `comment' for #<Forum:0x444d518>

使用以下摘录:

end
 @comment = @forum.comment.create(comment_params) #highlighted
 redirect_to forum_path
end

4 个答案:

答案 0 :(得分:1)

您的论坛模型中可能缺少has_many :comments关联。看看吧。

或者,如果has_many关联退出,那么它允许您在任何论坛对象上调用“评论”,而不是“评论”。

如果您想为特定论坛创建评论,可以这样做:

@comment = Comment.create(comment_params) #create a comment associated with this forum.

答案 1 :(得分:1)

问题在于您的CommentsController中的这一行@comment = @forum.comment.create(comment_params)。 它应该是@comment = @forum.comments.create(comment_params)comments应为复数。

您的代码应为:

class CommentsController < ApplicationController
  def create
    @forum = Forum.find(params[:forum_id])
    @comment = @forum.comments.create(comment_params)
    redirect_to forum_path
  end

  private

  def comment_params
    params.require(:comment).permit(:body)
  end
end

答案 2 :(得分:0)

确保 $image->getAttribute('data-src') 模型中有comments个关联:

Forum

答案 3 :(得分:0)

所以,问题在于CommentController。

我更改了注释控制器来执行此操作:

def create
        @forum = Forum.find(params[:forum_id])

        @comment = Comment.new(comment_params)
        @comment.forum_id = @forum.id
        @comment.save!

        redirect_to forum_path(@forum)
    end


    private
        def comment_params
            params.require(:comment).permit(:body)
        end

似乎可以做到这一点。

感谢所有给出答案的人。