I'm building a database in Ruby on Rails using Mongoid that includes the following three collections Residence, Map, and Router:

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

I currently have one residence document, one map document, and one router document. My question is how to implement the has_many, belongs_to, and has_and_belongs_to_many relationships between the documents, so that the residence document references the _id of the router and the _id of the map, the map document references the _id of the router, and the router references the _id of the map.

Sorry if this is unclear, and thanks for any help!

Edit: Here is an explanation of the relationships: Many Maps (displaying different data) can be generated for each Residence. Each Residence has a Router, but may have more than one Router. The Router(s) is included on the map, but should not be embedded since it can exist without a map.

1

There are 1 best solutions below

3
On

I guess it should be

 class Residence
   has_many :routers
   has_many :maps
 end

 class Map
   has_many :routers
 end

 class Router
   belongs_to :map
 end

If not, can you please explain the real-world relationships between these objects?