You are not logged in.

  • Login

1

Wednesday, October 12th 2011, 12:45pm

Polymorphe N:M-Relation

Hi,

ich krieg grad ne Krise ;)
Mein Vorhaben ist es, eine polymorphe N:M-Relation umzusetzen. In der Datenbank soll das ganze so aussehen, wie in der angehängten Grafik.

Beschränken wir uns mal nur auf die Tabellen Lectures, Topics und den TopicHandler.

Meine Modelle sehen wie folgt aus:

Topic.rb

RubyOnRails Quellcode

1
2
3
4
5
6
7
8
class Topic < ActiveRecord::Base
 
  has_many :lectures, :through => :TopicHandlers, :source => :nameable, :source_type => "Lecture"
  has_many :people, :through => :TopicHandlers, :source => :nameable, :source_type => "Person"
  has_many :TopicHandlers
 
  belongs_to :topic, :foreign_key => "parent_id"
end


TopicHandler.rb

RubyOnRails Quellcode

1
2
3
4
class TopicHandler < ActiveRecord::Base
  belongs_to :topic
  belongs_to :nameable, :polymorphic => true
end


RubyOnRails Quellcode

1
2
3
4
5
6
7
8
9
10
class Lecture < ActiveRecord::Base
  belongs_to :person
 
  has_many :Topics, :through => :TopicHandlers
  has_many :TopicHandlers, :through => :nameable
 
 
  validates :person, :presence => true
  validates :title, :presence => true
end


Gut möglich dass dort mittlerweile mehr als ein Fehler drin ist.. hab recht viel dran rumgespielt.
Das Problem ist, dass ich keine Relation aufbauen kann.

Wenn ich mittels IRB versuche einem Lecture-Objekt ein Topic zuzuweisen (lectureobject.topics = ...), erhalte ich eine Exception das die Methode topics nicht bekannt ist. Umgekehrt genauso, sprich ich kann keinem Topic ein Lecture-Objekt zuweisen.
Gleiches passiert bei den Testfällen.

Sieht vielleicht jemand auf Anhieb meinen Fehler? ;)

Vielen Dank im Voraus :)
F0kus has attached the following image:
  • polymorph_n_m_db.PNG

2

Thursday, October 13th 2011, 10:21am

So, habe das Rätsel nun doch noch gelöst ;)

Hier folgen die drei angesprochenen Modell-Klassen:

RubyOnRails Quellcode

1
2
3
4
class Topic < ActiveRecord::Base
  has_many :lectures, :through => :TopicHandlers, :source => :nameable, :source_type => "Lecture"
  has_many :TopicHandlers
end


RubyOnRails Quellcode

1
2
3
4
class TopicHandler < ActiveRecord::Base
  belongs_to :nameable, :polymorphic => true
  belongs_to :topic
end


RubyOnRails Quellcode

1
2
3
4
5
class Lecture < ActiveRecord::Base
  belongs_to :person
  has_many :TopicHandlers, :as => :nameable
  has_many :topics, :through => :TopicHandlers
end


Wenn jemand doch noch was "besseres" hat, kann er es natürlich gerne posten. Ich markiere es dennoch erstmal als gelöst :)

Social bookmarks