Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete an embedded document in mongomapper?

I run a sinatra application with mongomapper. I have models called Movie(Document) and Cover(EmbeddedDocument). I embed covers into movies using

@movie.covers << @cover
@movie.save

This works great.

When I hit @movies.covers, I got the array of embedded documents. But I am not able to destroy the embedded document. I tried something like this:

@movie.covers.each do |c|
c.destroy
end

NoMethodError: undefined method `destroy' for #<Cover:0xb7b20734>
 from (irb):5
 from /usr/lib/ruby/gems/1.8/gems/mongo_mapper-0.6.8/lib/mongo_mapper/associations/proxy.rb:85:in `call'
 from /usr/lib/ruby/gems/1.8/gems/mongo_mapper-0.6.8/lib/mongo_mapper/associations/proxy.rb:85:in `method_missing'
 from /usr/lib/ruby/gems/1.8/gems/mongo_mapper-0.6.8/lib/mongo_mapper/associations/proxy.rb:85:in `each'
 from /usr/lib/ruby/gems/1.8/gems/mongo_mapper-0.6.8/lib/mongo_mapper/associations/proxy.rb:85:in `send'
 from /usr/lib/ruby/gems/1.8/gems/mongo_mapper-0.6.8/lib/mongo_mapper/associations/proxy.rb:85:in `method_missing'
 from (irb):4
 from :0

How to destroy it? It would be great if someone enlightens me how to update the embedded document.

like image 452
Deepak Avatar asked Dec 20 '09 14:12

Deepak


Video Answer


1 Answers

Covers are stored as an array within movie object, therefore you can do e.g.:

@movie.covers.clear
@movie.save

or if you want to be selective

@movie.covers.delete_if {|cover| cover.name == "bla"}
@movie.save
like image 54
Piotr Zolnierek Avatar answered Sep 25 '22 16:09

Piotr Zolnierek