0

I'm relatively new to ruby on rails and I need some help to model the following scenario:

  • The model contains Products and Services
  • A Service must be provided by a Product (it cannot exist without a provider/owner)
  • A Product can provide zero, one or many Services
  • A Product can consume zero, one or many Services
  • The provider (Product) can but is not automatically a consumer of the provided Service

Whats the best use of associations to be able to get:

  • provided Services (from Product)
  • consumed Services (from Product)
  • consumers of the Service (from Service)
  • the providing Product (from Service)

The problem is similar to this one Many-to-many Users and groups, but groups have owners (Users and Groups with Owner). But my Product is not necessarily a consumer of the provided Service.

Any help would be greatly appreciated!

Community
  • 1
  • 1
shaped
  • 306
  • 2
  • 4

1 Answers1

0

Something like this might work for you

Service belongs_to :provider, class_name: "Product" # services has provider_id
Product has_many :provided_services, class_name: "Service", foreign_key: :provider_id

Product has_many :products_consumed_services
Product has_many :consumed_services, through: :products_consumed_services
ProductsConsumedService belongs_to :product
ProductsConsumedService belongs_to :consumed_service, class_name: "Service"

Service has_many :products_consumed_services, foreign_key: :consumed_service_id
Service has_many :consumers, through: :products_consumed_services, source: :product

provided Services (from Product)

product.provided_services

consumed Services (from Product)

product.consumed_services

consumers of the Service (from Service)

service.consumers

providing Product (from Service)

service.provider
messanjah
  • 8,977
  • 4
  • 27
  • 40