Rails4:表单中的第一个参数在侧栏上的form_for中不能包含nil或为空

时间:2014-12-29 01:58:37

标签: ruby-on-rails ruby ruby-on-rails-4

我收到以下错误。

ArgumentError in Articles#index
Showing e:/xxx/app/views/shared/_comment_form.html.erb where line #1 raised: 
First argument in form cannot contain nil or be empty

我想要做的是始终在侧边栏上显示text_area,以便用户能够输入评论。

comments没有任何关系。

我应该在@comment还是articles_controller设置comments_controller吗?虽然我尝试了一些,但它们不起作用。

\应用\视图\布局\ application.html.erb

<!DOCTYPE html>
<html>
  <head>
...
  </head>
  <body>
    <%= render 'layouts/header' %>
    <div class="container">
      <div class="row">
        <aside class="span3">
        <section>
          <%= render 'shared/comment_form' %>
        </section>
        </aside>
        <aside class="span9">
          <%= yield %>
          <%= render 'layouts/footer' %>
          <%= debug(params) if Rails.env.development? %>
        </aside>
      </div>
    </div>
  </body>
</html>

\应用\视图\ shared_comment_form.html.erb

<%= form_for(@comment) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class="field">
    <%= f.text_area :content, placeholder: "Enter your comment..." %>
  </div>
  <%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>

\应用\控制器\ comments_controller.rb

class CommentsController < ApplicationController

  def new
    @comment = Comment.new
  end
  def create
    @comment = Comment.new(comment_params)
    if @comment.save
      flash[:success] = "Sent your comment."
      redirect_to root_url
    else
      redirect_to root_url
    end

  private

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

end

\应用\模型\ comment.rb

class Comment < ActiveRecord::Base
    default_scope -> { order('created_at DESC') }
    validates :content, length: { maximum: 100 }
end

\应用\控制器\ articles_controller.rb

class ArticlesController < ApplicationController
..
  def index
    @articles = Article.all(limit: 10)
  end
..

请告诉我如何避免此错误。

2 个答案:

答案 0 :(得分:2)

只需更改

<%= form_for(@comment) do |f| %>

\app\views\shared_comment_form.html.erb

<%= form_for(Comment.new) do |f| %>

答案 1 :(得分:0)

根据示例中当前编写代码的方式,您需要在控制器级别提供的@comment实例变量,以便在该表单中输入注释。如果您要在网站范围内使用此表单,最好在@comment类的before_action中提供ApplicationController实例变量,如下所示:

class ApplicationController < ActionController::Base
  before_action :create_comment

  def create_comment
    @comment = Comment.new
  end
end