轨道上的红宝石 - 无法创建注释.无方法错误



我正在创建我的第一个 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

论坛控制器是自动生成的,我没有换进去。(使用rail生成脚手架论坛生成,如果你还想看,请告诉我(

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 %>

这是来自轨道的错误:

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

摘录如下:

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

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

或者,如果has_many关联退出,则允许您对任何论坛对象调用"评论",而不是"评论"。

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

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

问题出在 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

确保在Forum模型中具有comments关联:

class Forum < ApplicationRecord
  has_many :comments
end

所以,问题出在CommentsController上。

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

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

似乎做到了。

感谢所有给出答案的人。

最新更新