ActiveRecord :: HasManyThroughAssociationPolymorphicSourceError [英] ActiveRecord::HasManyThroughAssociationPolymorphicSourceError

查看:75
本文介绍了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

但是,如果我拔出Player.first并要求其结构,它会给出:

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'.

但是它应该能够生成SQL查询,在该查询中找到具有其ID的所有player_structures,然后根据structure_id和structure_type来获取结构.为什么会失败,如何有效构造多态联接表?

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?

如果我手动完成我想做的事情,它将起作用:

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

player_structures.collect(&:structure)

铁路,是吗?

推荐答案

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

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.

这篇关于ActiveRecord :: HasManyThroughAssociationPolymorphicSourceError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆