【发布时间】:2015-08-01 02:05:24
【问题描述】:
我正在学习 Rails 教程,并且刚刚将 Comment 模型与我的 Article 模型相关联。
我有一个视图文件,它在此处显示一篇文章及其所有 cmets (app/views/articles/show.html.erb):
<p>
<strong>Title:</strong>
<%= @article.title %>
</p>
<p>
<strong>Text:</strong>
<%= @article.body %>
</p>
<h2>Comments</h2>
<% @article.comments.each do |comment| %>
<p>
<strong>Commenter:</strong>
<%= comment.commenter %>
</p>
<p>
<strong>Body:</strong>
<%= comment.body %>
</p>
<% end %>
<h2>Add a comment:</h2>
<%= form_for([@article, @article.comments.build]) do |comment| %>
<p>
<%= comment.label :commenter %>
<%= comment.text_field :commenter %>
</p>
<p>
<%= comment.label :body %>
<%= comment.text_area :body %>
</p>
<p>
<%= comment.submit %>
</p>
<% end %>
这样排列的代码——添加评论表单上方显示的 cmets——在浏览器中一切正常
但是,当我重新排列以使评论表单位于 cmets 部分上方时,如下所示:
<p>
<strong>Title:</strong>
<%= @article.title %>
</p>
<p>
<strong>Text:</strong>
<%= @article.body %>
</p>
<h2>Add a comment:</h2>
<%= form_for([@article, @article.comments.build]) do |comment| %>
<p>
<%= comment.label :commenter %>
<%= comment.text_field :commenter %>
</p>
<p>
<%= comment.label :body %>
<%= comment.text_area :body %>
</p>
<p>
<%= comment.submit %>
</p>
<% end %>
<h2>Comments</h2>
<% @article.comments.each do |comment| %>
<p>
<strong>Commenter:</strong>
<%= comment.commenter %>
</p>
<p>
<strong>Body:</strong>
<%= comment.body %>
</p>
<% end %>
我在页面底部留下了一个标记为评论者和正文的 html 元素,但其中没有任何内容。例如,如果我对文章发表过一次评论,它会显示预期的评论,但还会在其下方显示一个额外的空白评论。在最初的代码安排下,没有额外的空白注释,只有我在文章上写的单个预期注释。
为什么像这样重新排列文本会在底部添加一个空白注释?
我的文章控制器显示操作:
def show
@article = Article.find(params[:id])
end
我的 cmets 控制器创建动作:
def create
@article = Article.find(params[:article_id])
@comment = @article.comments.create(comment_params)
redirect_to article_path(@article)
end
【问题讨论】: