1

現在、UserModel (Devise)、ArticleModel、CommentModel の 3 つのモデルがあります。

私はモンゴイドで働いています。

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

私の記事/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

私のコメント_コントローラー

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

今私の記事/ショーにID付きのコメントが表示されますが、完全に空で、このオブジェクトがどこから来たのかわかりません...

4

1 に答える 1

1

あなたの問題はこの行にあります:

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

を呼び出すと@article.comments.build、新しいコメントを作成して に追加し@article.commentsます。コメントを繰り返し処理すると、作成したばかりの空のコメントが表示されます。

の代わりに[@article, @article.comments.build]、 を使用します[@article, Comment.new]

于 2012-09-13T15:15:51.233 に答える