Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid how to insert embedded record?

I've got 2 classes... Articles and Comments (which are embedded in Articles).

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

and another one

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

  embedded_in :article, :inverse_of => :comments
end

The Json representation of this mongodb document is:

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

How do I insert another comment in this document using mongoid on rails?

Thanks Fak

like image 408
Fakada Avatar asked Feb 19 '23 09:02

Fakada


1 Answers

I've managed to do it...

At comments controller:

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

then i find the object i want to add a comment... and create it

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

Thanks guys...

like image 188
Fakada Avatar answered Feb 26 '23 21:02

Fakada