Reputation: 15129
Given
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
CarMake
or CarModel
should have additional foregin keys (making managing of makes/models isolated and independent),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
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:
Upvotes: 0
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