Polymorphe N:M-Relation

Diese Seite verwendet Cookies. Durch die Nutzung unserer Seite erklären Sie sich damit einverstanden, dass wir Cookies setzen. Weitere Informationen

  • 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

    Quellcode

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


    TopicHandler.rb

    Quellcode

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


    Quellcode

    1. class Lecture < ActiveRecord::Base
    2. belongs_to :person
    3. has_many :Topics, :through => :TopicHandlers
    4. has_many :TopicHandlers, :through => :nameable
    5. validates :person, :presence => true
    6. validates :title, :presence => true
    7. 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 :)
    Bilder
    • polymorph_n_m_db.PNG

      136,64 kB, 1.220×821, 1.216 mal angesehen
  • So, habe das Rätsel nun doch noch gelöst ;)

    Hier folgen die drei angesprochenen Modell-Klassen:

    Quellcode

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


    Quellcode

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


    Quellcode

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


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