【问题标题】:form_for first argument nil error in Rails with defined associations具有定义关联的 Rails 中的 form_for 第一个参数 nil 错误
【发布时间】:2016-04-18 23:12:57
【问题描述】:

我正在使用 Rails 构建一个简单的博客应用程序,并且我正在尝试创建为帖子提交评论的功能。但是,我不断收到此错误

表单中的第一个参数不能包含 nil 或为空

<h3> Submit a Comment </h3>

<%= form_for [@post, @comment] do |c| %> 
//Error is here, @comment appears to be nil and I'm not sure why 
//(I've checked both cases)

  <%= c.label :body, "Comment: " %>
  <br />
  <%= c.text_area :body %>

我查看了其他有类似问题但找不到解决方案的帖子。任何帮助将不胜感激

class CommentsController < ApplicationController

  def create
    @post = Post.find params[:post_id]

    comment_params = params.require(:comment).permit(:body)

    @comment = Comment.new comment_params
    @comment.post = @post
    # Why is my comment nil?

    if @comment.save
      redirect_to post_path(@post), notice: "Comment successful"
    else
      flash[:alert] = "Comment unsuccessful. Please do not enter an empty comment"
      render "/posts/show"
    end

  end

  def destroy
    # To be implemented
  end

end

编辑:已解决,忘记在我的 Post 控制器的 show 方法中添加 @comment = Comment.new

谢谢大家!

【问题讨论】:

  • 你的控制器是什么样子的?
  • 添加了我的 cmets 控制器

标签: ruby-on-rails ruby


【解决方案1】:

您正在创建一条新评论。您应该:

A.在控制器中的某处有@comment = Comment.new

B.使用

立即实例化它
form_for [@post, Comment.new] do |c| #...

【讨论】:

  • 嗯,我的控制器里有这个 - 除非我在某处有语法错误?
  • 具体来说,它应该在您的帖子控制器的show 方法中(假设这是提供添加评论选项的地方)
  • 啊,原来如此!谢谢!
  • @BruceWayne 如果我已经回答了您的问题,请记住接受答案(单击复选标记)。
猜你喜欢
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多