【问题标题】:Rails `has_many` associationRails `has_many` 关联
【发布时间】:2017-11-20 19:16:39
【问题描述】:

我刚开始学习 Rails,对关联有点困惑。

比如说,我有一个Car,它可以属于OwnerRenterCompany,并且只能属于其中一个和一个@ 987654325@、RenterCompany 可以有多个Cars

您建议我如何对这个场景进行建模? Car 表上是否应该有三个外键,分别对应 owner_idrender_idcompany_id?或者为它们中的每一个设置某种连接表,这将导致如下结果:

|车牌号 |所有者 ID | |--------|----------| | 1 | 1 | | 2 | 1 | | 3 | 1 |

或者还有其他方法可以实现吗?同时考虑到可以添加更多的家属(更多的租户、业主等群体)。

提前致谢。

【问题讨论】:

    标签: sql ruby-on-rails ruby


    【解决方案1】:

    这是一个使用多态关联的经典示例。

    class Car
      belongs_to :possessor, polymorphic: true
    end
    
    
    class Owner
      has_many :cars, as: :possessor
    end
    
    class Renter
      has_many :cars, as: :possessor
    end
    
    class Company
      has_many :cars, as: :possessor
    end
    

    cars 表中有两个新字段,possessor_typepossessor_id,您可以通过迁移添加它们,您可以添加其他可能拥有汽车的模型,无需添加更多列给cars

    【讨论】:

      【解决方案2】:

      一种可能的方法:使CarOwnerRenterCompany 上有外键。

      这是一个例子。

      class Car < ApplicationRecord
          belongs_to :owner
          belongs_to :renter
          belongs_to :company
      end
      
      class Owner < ApplicationRecord
          has_many :cars
      end
      
      class Renter < ApplicationRecord
          has_many :cars
      end
      
      class Company < ApplicationRecord
          has_many :cars
      end
      
      汽车表 编号|所有者 ID |租客ID | company_id | - |------------|------------|------------| 1 | 1 | 1 |2 | 2 | 1 | 1 |1 | 3 | 3 | 2 |1 |

      The has_many Association

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多