HABTM与多态性的关系

时间:2013-08-23 20:57:55

标签: ruby-on-rails has-and-belongs-to-many polymorphic-associations

  • 我有一个可以链接到许多结构的人(结构是多态的)
  • 我有一个场地,可以有很多人,作为一个结构。
  • 我有一个期刊,可以有很多人,作为一个结构。

这是我的模型化:

class Venue < ActiveRecord::Base
  has_many :structure_people, :as => :structure
  has_many :people, :through => :structure_people
end

class Journal < ActiveRecord::Base
  has_many :structure_people, :as => :structure
  has_many :people, :through => :structure_people
end

class Person < ActiveRecord::Base
  has_many :structure_people
  has_many :structures, :through => :structure_people
end

class StructurePerson < ActiveRecord::Base
  belongs_to :structure, polymorphic: true
  belongs_to :person
end

我的问题:

  • 当我试图让人们在场地或日记上时,它有效。酷:))

BUT

  • 当我试图在一个人身上得到结构时,我有一个错误:

    ActiveRecord :: HasManyThroughAssociationPolymorphicSourceError:在多态对象'Structure#structure'上没有has_many:通过关联'Person#structures'。

任何人都可以帮我解决这个问题吗?

非常感谢。

克里斯托夫

1 个答案:

答案 0 :(得分:0)

我认为这是对Rails的限制,因为has_many关联会自动猜测class_name。但多态关联可能会返回多个class_name。你介意用这个:

class Person < ActiveRecord::Base
  has_many :structure_people
  has_many :venues, :through => :structure_people
  #Journal is the same.
end

class StructurePerson < ActiveRecord::Base
  belongs_to :structure, polymorphic: true
  belongs_to :venue, :foreign_key => 'structure_id', :conditions => {:structure_type => 'Venue'}
  belongs_to :person
end

虽然这是一个丑陋的解决方案......

我认为你可以选择另一种方式。

class Person < ActiveRecord::Base
  has_many :structure_people

  def structures
    structure_people.map(&:structure)
  end
end

你不能得到has_many的链接函数,但你可以得到多态结构:)