Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord::HasManyThroughAssociationPolymorphicSourceError

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?

like image 655
Chris Avatar asked Dec 15 '12 19:12

Chris


1 Answers

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.

like image 200
jsquirrelz Avatar answered Oct 15 '22 06:10

jsquirrelz