的ActiveRecord :: HasManyThroughAssociationPolymorphicSourceError

我需要一个玩家拥有许多结构和属于玩家的结构。 结构是一种多态关系。

class Player  player_structures end class PlayerStructures < ActiveRecord::Base belongs_to :structure, polymorphic: true belongs_to :player end class StructureA  :structure has_one :player, :through => :player_structure end class StructureB  :structure has_one :player, :through => :player_structure end 

但是如果我拉出Player.first并询问它的结构,它会给出:

 ActiveRecord::HasManyThroughAssociationPolymorphicSourceError: Cannot have a has_many :through association 'Player#structures' on the polymorphic object 'Structure#structure'. 

但它应该能够生成一个SQL查询,在其中找到所有带有id的player_structures,然后根据structure_id和structure_type获取结构。 为什么这会失败,我怎样才能有效地构建多态连接表?

UPDATE

如果我按手动方式执行操作,则可以:

 player_structures.collect(&:structure) 

Rails,你不这样做吗?

我认为你需要更具体地定义你的Player模型中的关系。 例如:

 class Player < ActiveRecord::Base has_many :player_structures has_many :structureas, :through => player_structures, :source => :structure, :source_type => 'StructureA' has_many :structurebs, :through => player_structures, :source => :structure, :source_type => 'StructureB' end 

然后你可以创建一个方法,它将返回关系中定义的所有结构,而不必单独访问每个结构。