2

Evening all,

I've sat here scratching my head for the last few hours over this.

I have a very simple comments model attached to an article model. Issue is, there seems to be a blank comment at the end of every articles comments section. If i try and use a method like capitalize it errors out with "capitalize on nil class", also if i put the comments in a div with a grey background for each comment (facebook style) a blank box appears at the end of an articles comments. Does anyone know whats going on?

Anyway heres the code: Comments controller

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

comments Model

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"

comment form

<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>

comments show

<legend>Comments</legend>

    <% comments.each do |comment| %>
        <sabon><%= comment.name %></sabon><br>
        <p><%= comment.content %></p>
        <hr>
        <% end %>

bottom of article show

<%= render partial: "comments/form", locals: { article: @article } %><br><br>
<%= render partial: "comments/show", locals: { comments: @article.comments }%>

routes

resources :articles do
    resources :comments
  end

any help would be great thanks guys, thanks in advance Andy, if you need more code just shout.

4

1 回答 1

5

在评论表单行中@article.comments.build创建新的评论对象。表单的呈现发生在呈现之前,comments/show因此新的空白 Comment 对象存在于@article.comments集合中。

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

@article.comments.reject(&:new_record?)
于 2012-09-26T06:25:41.847 回答