【发布时间】:2026-01-22 00:40:01
【问题描述】:
我收到以下错误。
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 以便用户能够输入 cmets。
comments 没有任何关系。
我应该在articles_controller 和comments_controller 中设置@comment 吗?虽然我尝试了一些,但它们不起作用。
\app\views\layouts\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>
\app\views\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 %>
\app\controllers\cmets_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
\app\models\comment.rb
class Comment < ActiveRecord::Base
default_scope -> { order('created_at DESC') }
validates :content, length: { maximum: 100 }
end
\app\controllers\articles_controller.rb
class ArticlesController < ApplicationController
..
def index
@articles = Article.all(limit: 10)
end
..
请告诉我如何避免这个错误。
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4