对象被嵌入错误的父类mongoid中

时间:2014-06-04 16:19:06

标签: ruby-on-rails-3 mongodb mongoid

我目前正在尝试使用MongoID将CSV加载到我的MongoDB。除了嵌入的文档保存在同一根文档层之外,它的工作范围很广。 基本上,目前有一个信息文档,其中包含有关建筑物的信息。根据信息文件我嵌入地板和楼层我可以嵌入房间。类似于以下结构:

Information
   Floors
     Rooms 
       :name
       :thermostat_zone

我的测试CSV包含以下信息:

floor   room    zone
1       101      A
1       102      A
1       102      B
1       104      C
1       105      D
1       106      E
1       107      F
1       108      G
4       109      G
2       201      H
2       202      I
2       204      J
2       207      J
2       209      K
2       208      L
2       210      M
3       214      N
3       215      O
3       216      P
3       225      Q

唯一的问题是所有房间目前都嵌在第一层,而且我想有关于物体持久性的事情发生了很多事情,每当我花时间从装载环中打印出地板时,每层都打印出来。我真的希望有人可以帮我解决这个问题!我来自PHP / MYSQL背景,所以这对我来说是新的。

@building_id = params[:building_id]
    owner = Owner.where('buildings._id' => Moped::BSON::ObjectId(@building_id)).first
    @building =  owner.buildings.find(@building_id)
    @building.information.floors.destroy


    CSV.foreach(params[:file].path, headers: true) do |row|
        floor_name = row['floor']
        room_name = row['room']
        zone_name = row['zone']
        floor = Floor.new
        floor = @building.information.floors.where('name' => floor_name).first
        if !floor || floor == nil
           floor = Floor.new
          floor.name = floor_name
          floor.information = @building.information
          floor.save
        end


        room = Room.new
        room.floor = floor
        room.name = room_name
        room.zone = zone_name
        room.save 
    end 

此外,还需要Room.rb和Information.rb的代码:

class Room
 include Mongoid::Document
  embedded_in :floor, :inverse_of => :rooms

  field :name
  field :zone
end

Information.rb :(缩小到只是嵌入东西以使其更容易)

#Building information
class Information
  include Mongoid::Document
  embeds_many :floors, :cascade_callbacks => true


end

谢谢!

1 个答案:

答案 0 :(得分:0)

替换此

if !floor || floor == nil
  floor = Floor.new

if !floor || floor == nil
  floor = @building.information.floors.create!()
  # OR
  floor = @building.information.floors.create!(name: 'name', zone: 'A')

同样适用于房间 替换这个

room = Room.new

用这个

room = floor.rooms.create!()
# OR
room = floor.rooms.create!(name: 'name', zone: 'B')

这是因为mongoid没有使用child.parrent_attr = parent设置嵌入式文档的父级无法正常工作...