4

我有 2 个课程...文章和评论(嵌入在文章中)。

class Article
   include Mongoid::Document
   field :name, type: String
   field :content, type: String
   field :published_on, type: Date

   validates_presence_of :name

   embeds_many :comments
end

还有一个

class Comment
  include Mongoid::Document
  field :name, type: String
  field :content, type: String

  embedded_in :article, :inverse_of => :comments
end

此 mongodb 文档的 Json 表示形式为:

{
   _id:ObjectId("50ae35274b6b5eaa77000001"),
   author_id:ObjectId("50ae3b1e4b6b5e8162000001"),
   comments:[
      {
         _id:ObjectId("50ae380e4b6b5e0c34000001"),
         name:"fak",
         content:"i like this article
      }

   ],
   content:"article about nothing",
   name:"my sweet article",
}

如何使用 mongoid on rails 在本文档中插入另一条评论?

谢谢法克

4

1 回答 1

8

我已经成功了...

在评论控制器:

def create
  @article = Article.find(params[:article_id])
  @comment = @article.comments.create!(params[:comment])
  redirect_to @article, :notice => "Comentario criado!"
end

然后我找到我想添加评论的对象......并创建它

@photox=Photo.find_by(name: "foto xpto")
@photox.comments.create(:comment=>"NOVO COMENTARIO")

多谢你们...

于 2012-11-22T18:03:25.450 回答