简体   繁体   中英

Rails application planning associations?

I am making a cost of service comparison website that will have Services, and Providers. All the Providers will have a unique cost for each different service they offer. I want to be able to let my website viewers see a comparison of the cost each Provider charges for a particular service.

How should I set up this association? Would Services belong to Providers or Providers belong to Services?

In the application you would select a Service, and then see what each Provider charges for that service. I would also like to be able to select a Provider and see a list of their services if possible.

Would Services belong to Providers or Providers belong to Services?

Neither. Products and Services is a many-to-many relationship, so you need a joining record between products and services, which is also where you would need to store the price for the given provider's implementation of that service. This is an extremely typical use of has_many :through .

You might consider a joining record called something like "ProvidedService":

class Provider
  has_many :provided_services
  has_many :services, through: :provided_services

class ProvidedService
  belongs_to :provider
  belongs_to :service
  validates :price, presence: true

class Service
  has_many :provided_services
  has_many :services, through: :provided-services

By way of example, "Bell" and "Rogers" would be Providers (these are Canadian phone companies) and "Long Distance" would be a Service.

The joining ProvidedService between Bell and Long Distance might have a price of 24.99. The join between Rogers and Long Distance might have a price of 23.99.

this is not an 1-n relation, so we cannot use has_one and belongs_to . This is a 'nn' relation, so you can use has_and_belongs_to_many or has_many ..., through: ...

You probably need the has-and-belongs-to-many relationship here. The last case that you've mentioned:

In the application you would select a Service, and then see what each Provider charges for that service. I would also like to be able to select a Provider and see a list of their services if possible.

You can do this comfortably with the has-and-belongs-to-many association.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM