我在 Rails 中有两个具有 NN 引用关系的 Mongoid 文档类,如下所示:
class Band
include Mongoid::Document
field :name, type: String
field :_id, type: String, default: ->{ name }
has_and_belongs_to_many :tags
end
class Tag
include Mongoid::Document
field :name, type: String
field :_id, type: String, default: ->{ name }
has_and_belongs_to_many :bands
end
然后我为每个实例创建新实例并将它们关联起来:
2.0.0p247 :014 > band = Band.new(name: "beetles")
=> #<Band _id: beetles, name: "beetles", tag_ids: nil>
2.0.0p247 :015 > tag = Tag.new(name: "rock")
=> #<Tag _id: rock, name: "rock", band_ids: nil>
2.0.0p247 :016 > band.tags << tag
MOPED: 127.0.0.1:27017 COMMAND database=admin command={:ismaster=>1} (1.3745ms)
MOPED: 127.0.0.1:27017 UPDATE database=band_dev collection=bands selector={"_id"=>"beetles"} update={"$addToSet"=>{"tag_ids"=>{"$each"=>["rock"]}}} flags=[] (0.2341ms)
=> [#<Tag _id: rock, name: "rock", band_ids: ["beetles"]>]
这里调用数据库来更新驱动程序类(在本例中为“band”)。问题是这些实例都没有保存并且是全新的记录!
2.0.0p247 :017 > band.new_record?
=> true
2.0.0p247 :018 > tag.new_record?
=> true
那么为什么要为未保存的文档执行数据库往返呢?有没有可以关闭的设置?
版本信息:
mongoid (4.0.0 80ed36f)
moped (1.5.1)
origin (1.1.0)
bson (1.8.6)
bson_ext (1.8.6)
rails (4.0.0)
OS: Ubuntu 12.04 LTS
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux]