【问题标题】:has_many with multi-level hierarchy and single table inheritancehas_many 具有多级层次结构和单表继承
【发布时间】:2010-01-25 22:55:35
【问题描述】:

在我的 Rails 应用程序中,我有以下类型的多级层次结构:

class Vehicle < ActiveRecord::Base end
class RoadVehicle < Vehicle end
class Car < RoadVehicle end
class Buss < RoadVehicle end

然后我有一个像这样引用中间级别的类:

class Garage < ActiveRecord::Base
  has_many :road_vehicles
end

在这个简化的示例中,我为车辆表提供了一个类型列以启用单表继承。此外,它包含一个garage_id 列,以启用has_many 关系。当我创建一个新车库并添加汽车和公共汽车时,所有这些都按预期添加到数据库中。但是,当我稍后检索车库对象并检查 road_vehicles 集合时,它是空的。谁能告诉我我做错了什么?

【问题讨论】:

    标签: ruby-on-rails associations single-table-inheritance


    【解决方案1】:

    在使用单表继承模型设置关联时,您需要引用父模型,以便关联可以推断出表名。因此,在您的 Garage 课程中,您需要:

    has_many :vehicles
    

    如果要限制关联到RoadVehicles,可以添加条件:

    has_many :vehicles, :conditions => {:type => ['Car', 'Bus']}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-16
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多