嗨大家我用mongomapper运行sinatra应用程序。我有一些名为Movie(Document)和Cover(EmbeddedDocument)的模型。我使用
将封面嵌入到电影中@movie.covers << @cover
@movie.save
这很有效。 当点击@ movies.covers时,我得到了一系列嵌入式文档。 但我无法破坏嵌入式文档。我试过这样的事情
@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
任何人都可以如何摧毁它吗?如果有人启发我如何更新嵌入式文档,那就太好了。
答案 0 :(得分:15)
封面存储为电影对象中的数组,因此您可以执行以下操作:
@movie.covers.clear
@movie.save
或者如果你想要有选择性
@movie.covers.delete_if {|cover| cover.name == "bla"}
@movie.save
答案 1 :(得分:1)
如果您根据名称等属性进行删除,但是如果您已经知道了ID并想删除它,则可以使用p-rob's tubmlr post中的这个技巧:
def destroy
@phone_number = @person.phone_numbers.find(params[:id])
@person.phone_numbers.delete_if{|phone_number| phone_number.id == @phone_number.id}
if @person.save
redirect_to @person
else
flash[:error] = "dag, yo."
end
end
我真的很挣扎:(
答案 2 :(得分:0)
这是一个quick and dirty complete gist,用于从关联中删除嵌入的文档。在这里重复:
class Period
include MongoMapper::EmbeddedDocument
key :text, String
embedded_in :schedule
def to_s
text
end
end
class Schedule
include MongoMapper::Document
key :name, String
many :periods
def to_s
text = "#{name}, periods: " + periods.join(', ')
end
end
s1 = Schedule.create(:name => "Thursday",
:periods => [
Period.new(:text => "Morning"),
Period.new(:text => "Afternoon"),
Period.new(:text => "Evening")
])
puts s1
#Thursday, periods: Morning, Afternoon, Evening
s1.periods.delete_if{|p| p.text == 'Afternoon'}
s1.save
puts s1
# Thursday, periods: Morning, Evening