简单的Rails评论添加额外的空白评论

dod*_*747 2 ruby comments ruby-on-rails associations

晚上好,

过去几个小时,我坐在这里摸不着头脑.

我有一个非常简单的评论模型附加到文章模型.问题是,每篇文章评论部分的末尾似乎都有一个空白的评论.如果我尝试使用像"大写nil类"那样大写错误的方法,如果我将评论放在每个评论(Facebook样式)的灰色背景的div中,文章末尾会出现一个空白框评论.有谁知道发生了什么?

无论如何继承人代码:评论控制器

def create
    @article = Article.find(params[:article_id])
    @comment = @article.comments.create(params[:comment])
    if @comment.save
      flash[:success] = "Comment created"
      redirect_to @article
    else
      flash[:error] = "Something went wrong"
      redirect_to @article
    end
  end

  def destroy
    @article = Article.find(params[:article_id])
    @comment = @article.comments.find(params[:id])
    @comment.destroy
    redirect_to @article
  end
end
Run Code Online (Sandbox Code Playgroud)

评论模型

attr_accessible :name, :content

  belongs_to :article
  validates_presence_of :article_id
  validates_presence_of :content, length: { maximum: 300 }

  default_scope order: "comments.created_at DESC"
Run Code Online (Sandbox Code Playgroud)

评论表

<a href='#', id='comments-form', class="btn btn-large">Add a comment</a>
    <div id="comment">
    <%= form_for([@article, @article.comments.build]) do |f| %>

        <%= f.label :name %>
        <%= f.text_field :name %>

        <%= f.label :content %>
        <%= f.text_field :content %>

        <br>
        <%= f.submit "Create", class: "btn btn-large" %>
       <% end %>
    </div>
Run Code Online (Sandbox Code Playgroud)

评论显示

<legend>Comments</legend>

    <% comments.each do |comment| %>
        <sabon><%= comment.name %></sabon><br>
        <p><%= comment.content %></p>
        <hr>
        <% end %>
Run Code Online (Sandbox Code Playgroud)

文章底部显示

<%= render partial: "comments/form", locals: { article: @article } %><br><br>
<%= render partial: "comments/show", locals: { comments: @article.comments }%>
Run Code Online (Sandbox Code Playgroud)

路线

resources :articles do
    resources :comments
  end
Run Code Online (Sandbox Code Playgroud)

任何帮助都会很棒,谢谢你们,感谢提前安迪,如果你需要更多的代码只是大喊大叫.

Cas*_*der 5

在注释表单行中@article.comments.build创建新的Comment对象.在渲染之前渲染表单,comments/show因此新的空白Comment对象出现在@article.comments集合中.

更新 您可以从注释中排除新创建的对象,例如:

@article.comments.reject(&:new_record?)
Run Code Online (Sandbox Code Playgroud)