has_many通过关联可以是多态的吗?

时间:2014-09-06 04:16:05

标签: ruby activerecord

我有一个有很多飞行员的船模。飞行员可以是角色或派系。我可以使用has_many:through association来对此进行建模吗?

class Ship < ActiveRecord::Base
  has_many :pilots, :through => :pilot_assignments, :polymorphic => true
  has_many :pilot_assignments
end

class Character < ActiveRecord::Base
  has_many :ships, :through => :pilot_assignments
  has_many :pilot_assignments
end

class Faction < ActiveRecord::Base
  has_many :ships, :through => :pilot_assignments
  has_many :pilot_assignments
end

class PilotAssignment < ActiveRecord::Base
  belongs_to :ship
  belongs_to :pilot, :polymorphic => true
end

1 个答案:

答案 0 :(得分:0)

你可以尝试类似的东西:

class PilotAssignment < ActiveRecord::Base
  belongs_to :ship
  belongs_to :pilot, polymorphic: true
end

class Ship < ActiveRecord::Base
  # i'm not sure should be there some additional options or not (like as: :pilot)
  has_many :pilots, through: :pilot_assignments
  has_many :pilot_assignments
end

class Character < ActiveRecord::Base
  has_many :ships, through: :pilot_assignments
  has_many :pilot_assignments, as: :pilot
end

class Faction < ActiveRecord::Base
  has_many :ships, through: :pilot_assignments
  has_many :pilot_assignments, as: :pilot
end

PilotAssignment也应包含:pilot_typepilot_id