1

I currently have 3 Models, UserModel (Devise), an ArticleModel and an CommentModel.

I work with mongoid.

class Comment
  include Mongoid::Document
  field :body, type: String
  field :created_at, type: Time, default: DateTime.now
  belongs_to :article
  belongs_to :user
end

class Article
  include Mongoid::Document
  field :title, type: String
  field :body, type: String
  field :created_at, type: DateTime, default: DateTime.now
  has_many :comments
  belongs_to :user
end

class User
  include Mongoid::Document
  has_many :articles
  has_many :comments
end

my article/show.html.haml

.comments-form
        .row
    .span12
        = form_for([@article, @article.comments.build]) do |f|
            = f.text_area :body, :class => "span12", :rows => "3", :placeholder => "Your comment here..."
            = f.submit nil, :class => "btn"
.comments
    - @article.comments.each do |comment|
        .comment{:id => "#{comment.id}"}
            .row
                .span2
                    = image_tag("260x180.gif", :class => "thumbnail")
                .span10
                    = comment.body

my comments_controller

class CommentsController < ApplicationController
  def new
    @article = Article.find(params[:article_id])
    @comment = @article.comments.create(params[:comment])
    @comment.user = current_user
    @comment.save
    redirect_to article_path(@article, notice: "Comment posted.")
  end
end

now in my articles/show appears an comment with an id but completely empty and i just can't figure out where this object comes from...

cschaeffler
  • 453
  • 3
  • 5
  • 17
  • Your `new` action should be `create`, and it should use `@comment = @article.comments.build(params[:comment])` instead of `.create` which will attempt to persist the object. – user229044 Sep 13 '12 at 15:20

1 Answers1

1

Your problem is with this line:

= form_for([@article, @article.comments.build]) do |f|

When you call @article.comments.build, you're buildling a new comment and adding it to @article.comments. Further down when you iterate over your comments, you're seeing the empty one you just created.

Instead of [@article, @article.comments.build], use [@article, Comment.new].

user229044
  • 232,980
  • 40
  • 330
  • 338
  • Please don't add "thanks" comments. If you like an answer, upvote it. If it answered your question, [accept it](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). – user229044 Sep 13 '12 at 16:57