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",
}

レール上のモンゴイドを使用して、このドキュメントに別のコメントを挿入するにはどうすればよいですか?

ありがとう

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 に答える