0
  • I've got a Person who can be linked to many Structures (structure is polymorphic)
  • I've got a Venue, who can have many People, as a structure.
  • I've got a Journal, who can have many People, as a structure.

Here is my modelization :

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

My problem :

  • when i try to get people on a Venue or on a Journal, it works. Cool :)

BUT

  • when i try to get structures on a person, i've got an error :

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

Anyone could help me to solve this ?

Thanks a lot.

Christophe

krichtof
  • 83
  • 8

1 Answers1

0

I think it's a restriction of Rails, because has_many association will guess a class_name automatically. But polymorphic association may returns multiple class_name. Do you mind use this:

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

Although it is an ugly solution...

I think you can choose an alternative way.

class Person < ActiveRecord::Base
  has_many :structure_people

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

You can't get chaining function of has_many, but you can get polymorphic structures :)

Bigxiang
  • 6,252
  • 3
  • 22
  • 20
  • Thank you very much for your answer. But it's not exactly what I expect. I'd like to be able to get structures on a person (and not specifically venues). If I have on `class Person` `has_many :venues` and `has_many :journals`, I lose the interest of polymorphism. – krichtof Aug 24 '13 at 09:47
  • I updated the answer, I think you can't get polymorphic using has_many :through, but you can choose another way without chaining function. – Bigxiang Aug 24 '13 at 14:24
  • Thanks for this solution. I find also another solution. By using STI. Journal and Venue are subclasses of Structure. And by this way, I can use has_many and has_many :through – krichtof Aug 27 '13 at 13:34