0

扩展 Mongoid 关系文档中的示例,假设我有三个类......

class Band
  include Mongoid::Document
  embeds_many :albums
end

class Album
  include Mongoid::Document
  field :name, type: String
  embedded_in :band
  embeds_many :tracks
end

class Track
  include Mongoid::Document
  field :name, type: String
  field :length, type: String
  embedded_in :album
end

如何将曲目从一张专辑移动到另一张专辑?我已经尝试了明显的...

~/Projects/mongoid_testing (development) > Band.last.albums.first.tracks.first.update_attribute :album_id, Band.last.albums.second.id
☘ MongoDB (8ms) [mongoid_testing_development::Bands] QUERY selector={"$query"=>{}, "$orderby"=>{:_id=>-1}} flags=[:slave_ok] limit=-1 skip=0 batch_size=nil fields=nil
☘ MongoDB (0ms) [mongoid_testing_development::Bands] QUERY selector={"$query"=>{}, "$orderby"=>{:_id=>-1}} flags=[:slave_ok] limit=-1 skip=0 batch_size=nil fields=nil
☘ MongoDB (0ms) [mongoid_testing_development::Bands] UPDATE selector={"_id"=>"51005ceb93e53c2eec000012"} update={"$set"=>{"albums.0.tracks.0.album_id"=>"51005d2993e53c2eec000017"}} flags=[]
=> true
~/Projects/mongoid_testing (development) > Band.last
☘ MongoDB (0ms) [mongoid_testing_development::Bands] QUERY selector={"$query"=>{}, "$orderby"=>{:_id=>-1}} flags=[:slave_ok] limit=-1 skip=0 batch_size=nil fields=nil
=> #<Band:0x007fa22725b1f8> {
           :_id => "51005ceb93e53c2eec000012",
      :albums => [
        [0] {
               "_id" => "51005d2293e53c2eec000016",
            "tracks" => [
                [0] {
                         "_id" => "5107d87993e53c7191000007",
                    "album_id" => "51005d2993e53c2eec000017",
                       "title" => "Pipeline"
                }
            ],
              "name" => "Violater"
        },
        [1] {
             "_id" => "51005d2993e53c2eec000017",
            "name" => "Construction Time Again"
        }
    ]
}

而且我已经尝试了不那么明显的...

class Track
  ...
  def move_to(new_album_id)
    _parent.albums.delete self
    _root.albums.find(new_album_id).tracks.push self
  end
end

但无论如何,我似乎都无法重新关联双嵌套嵌入文档。任何人都可以帮忙吗?谢谢。

4

1 回答 1

2

这是解决方案

new_parent = Band.first.albums.second
old_track = Band.first.albums.first.tracks.first

unless new_parent.id == old_track.parent.id
  new_parent.tracks << old_track.dup
  old_track.delete
end
于 2013-01-29T17:19:08.160 回答