我遇到了一个数据库设计问题,有人能不能指出我正确的方向。
我已经has_many了车辆,气缸,库存项目之间的关系。
气缸有很多要求。 到目前为止,一切正常。
class Vehicle < ApplicationRecord
has_many :inventory_items
has_many :cylinders, through: :inventory_items
end
class InventoryItem < ApplicationRecord
belongs_to :vehicle
belongs_to :cylinder
end
class Cylinder < ApplicationRecord
has_many :inventory_items
has_many :vehicles, through: :inventory_items
has_many :requirements
end
当前示例数据
车辆
id vehicle_type_id year make model
1 3 1999 honda acccord
2 3 2017 toyota corolla
3 3 2010 ford fiesta
圆柱体
id name
1 v2
2 v4
3 v6
4 v8
英维托里物品
id vehicle_id cylinder_id
1 1 2
2 1 3
3 2 1
4 2 2
5 2 3
6 2 4
7 3 2
要求
id cylinder_id item_id
1 1 1000
2 2 600
3 3 451
4 4 550
但我想改变这一点,因为气缸的要求会根据车辆而变化。 应气缸要求值取决于车辆值。
例如。
在车辆中 - 汽车环境
Cylinder.find(1(.requirements是item#1000在车辆 - 货车环境中
圆柱体查找(1(.要求是项目#189
Requirements.new( :cylynder_id => 1, :vehicle_id=>1, :item_id => 1000 (.save
Requirements.new( :cylynder_id => 1, :vehicle_id=> 2 :item_id => 189 (.save我该如何解决这个问题,请帮助我?
我相信这不是一个新的挑战,但是以前遇到过同样的情况,您在多对多关系关联中的两个选项是使用1. has_and_belongs_to_many不需要两个模型之间的直接关系,并且与连接模型没有任何其他关系2. has_many_through何时需要使用关系模型执行其他操作,例如验证、回调、添加额外属性等。在您的情况下,看起来气缸通过车辆有很多要求。您可能需要验证需求模型。因此,通过气缸、要求和车辆之间的关系进行另一种has_many将是我要做的。变得复杂,但它就是这样 - 我的两分钱!
首先通过 rails 的命名约定many_to_many关联中间表名应该是
CylinderVehicle
报价
除非使用 :join_table选项,活动记录通过使用 类名的词法顺序。因此,气缸和车辆之间的连接 模型将给出默认的连接表名称"CylinderVehicle" 因为"C"在词法排序中超过了"V"。