这可能无法完全回答您的问题,但如果您只想为气垫船担任两个角色,我会改为建立这样的关联
class Hovercraft < ActiveRecord::Base
belongs_to :pilot, :class_name => 'Ninja', :foreign_key => 'pilot_id'
belongs_to :copilot, :class_name => 'Ninja', :foreign_key => 'copilot_id'
end
class Ninja < ActiveRecord::Base
has_many :pilotings, :class_name => 'Hovercraft', :foreign_key => 'pilot_id'
has_many :copilotings, :class_name => 'Hovercraft', :foreign_key => 'copilot_id'
end
现在,如果您有更多的角色,或者如果您需要更多的灵活性,您可以使用第三种模型将它们链接在一起。
class Hovercraft < ActiveRecord::Base
has_many :hovercraft_roles
has_many :ninjas, :through => :hovercraft_roles
end
class HovercraftRole < ActiveRecord::Base
belongs_to :hovercraft
belongs_to :ninja
end
class Ninja < ActiveRecord::Base
has_many :hovercraft_roles
has_many :hovercrafts, :through => :hovercraft_roles
end
使用模型中的角色属性HovercraftRole
来指示它是“飞行员”还是“副驾驶”。