has_many 具有多级层次结构和单表继承
在我的 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 集合时,它是空的。谁能告诉我我做错了什么?
In my Rails app I have a multi-level hierarchy of the following kind:
class Vehicle < ActiveRecord::Base end
class RoadVehicle < Vehicle end
class Car < RoadVehicle end
class Buss < RoadVehicle end
Then I have a class referencing the middle level like so:
class Garage < ActiveRecord::Base
has_many :road_vehicles
end
In this simplified example, I have given the vehicles table a type column to enable single table inheritance. Additionally, it contains a garage_id column, to enable the has_many relationship. When I create a new garage and add cars and busses, all get added to the database as expected. However, when I later retrieve the garage object and inspect the road_vehicles collection, it is empty. Can anyone tell me what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当设置与单表继承模型的关联时,您需要引用父模型,以便关联可以推断出表名称。因此,在您的 Garage 类中,您需要:
如果您想将关联限制为 RoadVehicles ,您可以添加条件:
When setting up associations with single table inheritance models, you need to refer to the parent model so the associations can infer a table name. So, in your
Garage
class you need:If you want to restrict the association to
RoadVehicles
, you can add conditions: