7

我用 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

如何摧毁它?如果有人启发我如何更新嵌入式文档,那就太好了。

4

3 回答 3

15

封面存储为电影对象中的数组,因此您可以执行以下操作:

@movie.covers.clear
@movie.save

或者如果你想有选择性

@movie.covers.delete_if {|cover| cover.name == "bla"}
@movie.save
于 2009-12-20T20:43:32.610 回答
1

如果您基于名称等属性进行删除,则此方法有效,但如果您已经知道 id 并想要删除它,请使用p-rob 的 tubmlr 帖子中的此技巧:

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

我真的很挣扎:(

于 2010-09-23T04:56:31.250 回答
0

这是从关联中删除嵌入文档的快速而肮脏的完整要点。在这里重复:

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
于 2012-07-05T02:19:18.160 回答