如何在单个嵌入的Mongoid文档之间移动双嵌套的嵌入式Mongoid文档?

时间:2013-01-29 14:27:45

标签: ruby-on-rails ruby mongoid mongoid3

扩展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

但不管我似乎无法重新关联双嵌套嵌入式文档。有人可以帮忙吗?感谢。

1 个答案:

答案 0 :(得分: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