【问题标题】:Mongoid how to insert embedded record?Mongoid如何插入嵌入记录?
【发布时间】:2012-11-22 16:49:19
【问题描述】:

我有 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 在此文档中插入另一条评论?

谢谢 假的

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid


    【解决方案1】:

    我已经成功了……

    在 cmets 控制器处:

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

    谢谢大家...

    【讨论】:

      猜你喜欢
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-19
      相关资源
      最近更新 更多