的ActiveRecord :: HasManyThroughAssociationPolymorphicSourceError

Chr*_*ris 6 ruby polymorphic-associations jointable

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

class Player < ActiveRecord::Base
  has_many :player_structures
  has_many :structures, :through => player_structures
end

class PlayerStructures < ActiveRecord::Base
  belongs_to :structure, polymorphic: true
  belongs_to :player
end

class StructureA < ActiveRecord::Base
  has_one :player_structure, :as => :structure
  has_one :player, :through => :player_structure
end

class StructureB < ActiveRecord::Base
  has_one :player_structure, :as => :structure
  has_one :player, :through => :player_structure
end
Run Code Online (Sandbox Code Playgroud)

但如果我退出Player.first并询问其结构,它会给出:

ActiveRecord::HasManyThroughAssociationPolymorphicSourceError: Cannot have a has_many :through association 'Player#structures' on the polymorphic object 'Structure#structure'.
Run Code Online (Sandbox Code Playgroud)

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

UPDATE

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

player_structures.collect(&:structure)
Run Code Online (Sandbox Code Playgroud)

Rails,你不这样做吗?

小智 11

我认为您需要更具体地定义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
Run Code Online (Sandbox Code Playgroud)

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