2016-11-15 61 views
0

我建立一個數據庫的Ruby on使用Mongoid包括以下三個集合住宅,地圖,以及路由器的Rails:如何使用Ruby on Rails將文檔(ObjectId)添加到has_many和has_and_belongs_to_many關係中?

residence.rb

class Residence 
    include Mongoid::Document 
    include Mongoid::Timestamps 
    include Mongoid::Geospatial 

    has_many :maps, inverse_of: :residence 
    has_many :routers, inverse_of: :residence 

    field :address, type: String 
    field :resident, type: String 

end 

map.rb

class Map 
    include Mongoid::Document 
    include Mongoid::Timestamps 
    include Mongoid::Geospatial 

    belongs_to :residence, inverse_of: :maps 
    has_and_belongs_to_many :routers, inverse_of: :maps 
    embeds_many :pins 

    field :name, type: String 

    spatial_index "pins.loc" 

end 

router.rb

class Router 
    include Mongoid::Document 
    include Mongoid::Timestamps 
    include Mongoid::Geospatial 

    belongs_to :residence, inverse_of: :routers 
    has_and_belongs_to_many :maps, inverse_of: :routers 

    field :loc, type: Point 
    field :MAC, type: String 
    field :name, type: String 
    field :serial, type: String 

    spatial_index :loc 

end 

我目前有一個居住證件,一份地圖文件和一份路由器文件。我的問題是如何實現文檔之間的has_many,belongs_to和has_and_belongs_to_many關係,以便居住文檔引用路由器的_id和地圖的_id,地圖文檔引用路由器的_id和路由器引用地圖的_id。

對不起,如果這不清楚,並感謝您的幫助!

編輯:下面是關係的解釋: 可以爲每個住宅生成許多地圖(顯示不同的數據)。每個住宅都有一個路由器,但可能有多個路由器。路由器包含在地圖中,但不應嵌入,因爲它可以在沒有地圖的情況下存在。

回答

0

我想這應該是

class Residence 
    has_many :routers 
    has_many :maps 
end 

class Map 
    has_many :routers 
end 

class Router 
    belongs_to :map 
end 

如果沒有,請你解釋這些對象之間的真實世界的關係?

+0

可以爲每個住宅生成許多地圖(顯示不同的數據)。每個住宅都有一個路由器,但可能有多個路由器。路由器包含在地圖中,但不應嵌入,因爲它可以在沒有地圖的情況下存在。 –

+0

我已根據您的評論修改了關聯。 –

+0

我明白如何定義模型中的關係。我的問題是如何插入文件,同時指定哪些文件與之相關。 –

相關問題