ActiveRecord::HasManyThroughAssociationPolymorphicSourceError

浪子不回头ぞ 提交于 2019-12-10 04:34:02

问题


I need a player to have many structures and the structure to belong to the player. Structure is a polymorphic relationship.

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

But if I pull out Player.first and ask for its structures, it gives:

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

But it should be able to generate a SQL query where it finds all player_structures with its id, then fetches the structure based on the structure_id and structure_type. Why does this fail and how can I validly construct a polymorphic join table?

UPDATE

If I do what I want it to do manually, it works:

player_structures.collect(&:structure)

Rails, y u no do that?


回答1:


I think you need to be more specific in defining your relationships in your Player model. For example:

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

Then you can make a method that'll return all the structures defined in the relationships instead of having to access each one individually.



来源:https://stackoverflow.com/questions/13895622/activerecordhasmanythroughassociationpolymorphicsourceerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!