【问题标题】:rails 4 modeling many to many polymorphic associationsrails 4建模多对多多态关联
【发布时间】:2013-11-07 20:04:33
【问题描述】:

我正在为“如何建立关系建模”的第一步而苦苦挣扎?我关注了几个模型,

class CarMake  
end  

class Region  
end  

Class CarModel  
end  

关系是“汽车制造商”有许多模型属于零个或多个区域。例如假设本田在北美和亚洲拥有“思域”车型。本田也仅在欧洲拥有“ CivicMini”。模拟这些关系的最佳方法是什么?是不是每个 CarModel 通过 Region 都属于 CarMaker?

也很少有其他模型使用这种关系,

客户

class Customer  
  has_many :cars   
end  

这辆车引用了所有属性,如 CarMake、CarModel、Region,但是如何(我需要另一个类来存储这些属性并在“Car”中引用它吗?)

class Car  
  belongs_to :customer  
end  

【问题讨论】:

    标签: ruby-on-rails data-modeling polymorphic-associations


    【解决方案1】:

    在 Car 类中定义一个多态接口

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

    在 CarMaker 类中

    has_many :cars, as: :car_type
    

    在 CarModel 类中

    has_many :cars, as: :car_type
    

    在区域类中

    has_many :cars, as: :car_type
    

    每当您在汽车表中存储记录时......存储对象类型(CarMaker、CarModel、Region)和 id

    【讨论】:

    • Rubyist,感谢您的回复。因为,我以前从未使用过这个接口,所以它向我提出了一个问题,即如何将这些类中的每一个映射到包括客户在内的自己的表中?
    【解决方案2】:

    这对你有用吗?

    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
    

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

    这对您的用例有用吗?

    【讨论】:

      猜你喜欢
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多