我在“如何建模关系”的第一步中挣扎?我遵循了几个型号,

class CarMake  
end  

class Region  
end  

Class CarModel  
end  

关系是“汽车制造商”的许多模型属于零或更多区域。例如,假设本田在北美和亚洲具有“公民”模式。本田仅在欧洲才有“公民”。建模这些关系的最佳方法是什么?就像每个carmodel都属于穿过地区的汽车制造商吗?

还有其他模型使用这种关系,

顾客

class Customer  
  has_many :cars   
end  

这辆车引用了所有属性,例如Carmake,Carmodel,region,但是如何需要其他类来存储这些属性并在“汽车”中引用它?)

class Car  
  belongs_to :customer  
end  
有帮助吗?

解决方案

在汽车类中定义了多态界面

belongs_to :car_type(interface name change according to you), polymorphic: true

在汽车制造商课上

has_many :cars, as: :car_type

在Carmodel课程中

has_many :cars, as: :car_type

在地区类中

has_many :cars, as: :car_type

每当您将记录存储在汽车表中。...存储将是(汽车制造商,Carmodel,Region)和ID的对象类型

其他提示

这个适合您吗?

class Maker
   has_many :models
end

class Model
   has_many :regions
   belongs_to :maker
end

class Region
  belongs_to :model
end

class Car
  has_one :model
  belongs_to :customer
end

class Customer
  has_many :cars
end

因此,在这种情况下,客户可以拥有多辆相同或不同型号的汽车,并且该模型可以具有许多不同的区域,并且属于制造商。

这适用于您的用例吗?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top