oldhomemovie
oldhomemovie

Reputation: 15129

Many-to-many data model puzzle

Given

  1. 3 ActiveRecord models:

    class Dealer < ActiveRecord::Base
    end
    
    class CarMake < ActiveRecord::Base
      has_many :car_models
    end
    
    class CarModel < ActiveRecord::Base
      belongs_to :car_make
    end
    
  2. non of either CarMake or CarModel should have additional foregin keys (making managing of makes/models isolated and independent),
  3. adding join tables or associations is not prohibited and is welcome.

Problem

I need dealer to have assigned a desired subset of available car_makes and desired subset of car_models for each of respectively assigned car_make.

Example

Given this data:

       car_models            car_makes
------------------------   -------------
id  car_make_id    title   id      title
 1            1     Flex    1       Ford
 2            1   Fiesta    2  Chevrolet
 3            1    Focus    3    Mercury
 4            2   Impala    4     Nissan  
 5            2  Suburan
 6            3    Milan
 7            4   Altima

What I want is to do:

dealer1.his_makes  # => [Ford, Chevrolet, Mercury]
dealer1.his_models # => [Flex, Fiesta, Impala, Milan]

dealer2.his_makes  # => [Ford, Mercury, Nissan]
dealer2.his_models # => [Fiesta, Focus, Altima]

My question is:
Which associations/tables should I add to achieve this?.

Upvotes: 2

Views: 65

Answers (2)

David Aldridge
David Aldridge

Reputation: 52336

A join table between dealer and car makes would allow you to specify "desired car makes by dealer". If all the desired models were of the make specified in this table then I'd create a join table between DealerCarMakes and CarModels to specify the desired models for that make for that dealer.

While you could use a single table, there would be some issues:

  1. You'd need a distinct on the query that retrieves desirable car makes, which often indicates a lack of normalisation.
  2. Being able to specify a desirable car make would be dependent on there being a desirable car model for that make -- maybe not an issue here, but definitely an issue in other cases where there is not such a dependency.
  3. You could not have attributes at the DealerCarMake level, such as "desirable since date" or a value range.

Upvotes: 0

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

Add an Inventory model that belongs to Dealer, CarModel, and CarMake. Toss in a 'quantity' field just for fun.

You could argue that CarModel isn't necessary, but if it's a common query, seems like a reasonable spot to de-normalize.

Upvotes: 1

Related Questions