Mongoid querying DB while associating NEW unsaved records in a
has_and_belongs_to_many relationship
I have two Mongoid document classes in Rails with a N-N reference
relationship, as below:
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
Then I create new instances of each one and associate them:
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"]>]
Here a call is made to the database to update the driver class (in this
case the "band"). The problem is that neither of these instances were
saved and are brand new records!
2.0.0p247 :017 > band.new_record?
=> true
2.0.0p247 :018 > tag.new_record?
=> true
So why to perform a db roundtrip for an unsaved document? Is there a
setting where I can turn this off?
No comments:
Post a Comment