我认为您正在寻找基本的 Single-table Inheritance,因为前轮胎和后轮胎确实不是一回事,而是特定类型的轮胎。为此,您需要在表中添加一个type
字符串列tires
,并声明该类的两个子Tire
类:
class Motorcycle < ActiveRecord::Base
belongs_to :front_tire
belongs_to :back_tire
end
class Tire < ActiveRecord::Base
end
class FrontTire < Tire
has_many :motorcycles
end
class BackTire < Tire
has_many :motorcycles
end
这将允许您使用Tire.first
,它会返回一个FrontTire
or的实例BackTire
,它会有很多motorcycles
. 这满足您的Tire.first.motorcycles
要求。
m = Motorcycle.new
ft = FrontTire.new # id 1
bt = BackTire.new # id 2
m.front_tire = ft
m.back_tire = bt
m.save
Tire.first.motorcycles # returns FrontTire #1
# Or, find specifically by tire type
FrontTire.first.motorcycles # all motorcycles with this front-tire
BackTire.first.motorcycles # all motorcycles with this back-tire
或者,您可以简单地使用通用tires
关系,因为前轮胎和后轮胎是不同的类:
class Motorcycle
has_many :tires
end
class Tire < ActiveRecord::Base
end
class FrontTire < Tire
has_many :motorcycles, foreign_key: :tire_id
end
class BackTire < Tire
has_many :motorcycles, foreign_key: :tire_id
end
NpwMotorcycle.first.tires
将返回一个包含两个对象的数组,一个是 a 的FrontTire
实例,一个是 a 的实例BackTire
。您可能希望添加一个验证器以防止将多个前/后轮胎分配给同一辆摩托车。