I’m trying to figure out how to model a Device/Service relationship.
I’m using Rails 3 and MongoDB/Mongoid.
The Rails app is for monitoring IP networks.
- A device on the network (workstation, server, etc.) is represented using a Device model.
- A service is a service such as HTTP, SMTP, SSH and each service “type” (HTTP, SMTP, SSH) can be associated with many devices.
- Each service “type” may have some options that can be set when associated with
a specific device (I’m thinking HTTP could have a port option if the HTTP service isn’t
running on port 80 for example).
In the view when a user manually adds a device I need some way of allowing them to pick
the services they want the app to monitor.
Further, if the user tries to run an automatic device discovery I would like to go through the services the app supports and query the device to see if the device supports that service.
Lastly, a job runs at a certain interval to pull in new data from each device in the DB.
In that polling job I need some way of querying each service associated with the device and then saving the data (service up/down, etc.) that is specific to the device/service relationship. This is where I’m stuck. I don’t know how to do this.
Do I need a third model? How do I specify this data in my model?
Or perhaps I’m going about this all wrong and there is a better way of representing
what I want to do?
This is what my model code looks like now:
device.rb
class Device
include Mongoid::Document
field :name
field :ip_address
references_many :services
def polll
# psuedocode
for each service
query service
end
# save data back to DB
update_attributes(...)
end
end
service.rb
class Service
include Mongoid::Document
field :name
field :description
references_many :devices
end
In a relational database, what you would actually need is a has_many through call with a join model specified.
Here you would do the same for the Service model and add a Port model as the join one. However, since you’re using Mongo, I’m gonna suggest that you embed Service into Device. This makes querying much much easier and a Service really shouldn’t be managed without a Device present. Don’t worry about data duplication, because what you’ll have is a more natural representation of your data model.
Here’s a doc page for Mongoid’s syntax for associations, including the embedded ones, http://mongoid.org/docs/associations/