2013-07-21 45 views
0

我正在使用Rails,但這確實適用於任何OO/SQL系統。什麼是可以附加到不同類型的父模型的兒童模型的正確關聯?

我有一個筆記模型和一個評論模型。註釋可以有很多註釋。這很直接,但現在我想添加一個新的模型,LearningObjective,它也可以有很多評論。什麼是正確的方法來做到這一點?我能想到的唯一方法是在評論表中有一列,其中有父模型的名稱和一個parent_model_id列。否則,我必須在註釋表中有兩個單獨的列,一個用於note_id,另一個用於learning_objective_id,用於檢查哪一個爲null。

有沒有一個典型的模式用於這樣的情況?也許是一箇中間模型?

回答

0

你描述的場景通常是用多態性來解決的,這基本上就是你在你的問題中提出的理論。 Rails中的多態性是easy;一個例子:

class Comment < ActiveRecord::Base 
    belongs_to :commentable, polymorphic: true 
end 

class Note < ActiveRecord::Base 
    has_many :comments, as: :commentable 
end 

class LearningObjective < ActiveRecord::Base 
    has_many :comments, as: :commentable 
end 

您將有兩列在您的comments表來處理這種關係:commentable_typecommentable_id,這將分別是聯想的存儲類名和ID。

0

你可以使用這個路口表:

 
    +---------------------+ 
    | Comments   | 
    +---------------------+ 
    | commentID | comment | 
    +---------------------+ 

    +---------------+ 
    | Notes   | 
    +---------------+ 
    | noteID | note | 
    +---------------+ 

    +-------------------------+ 
    | LearningObjective  | 
    +-------------------------+ 
    | objectiveID | objective | 
    +-------------------------+ 

現在爲您十字路口:

 
    +------------------------------------+ 
    | NoteComment      | 
    +------------------------------------+ 
    | noteCommentID | commentID | noteID | 
    +------------------------------------+ 

    +------------------------------------------------------+ 
    | LearningObjectiveComment        | 
    +------------------------------------------------------+ 
    | learningObjectiveCommentID | commentID | objectiveID | 
    +------------------------------------------------------+ 

這是我會怎麼做,肯定還有其他的解決方案,以及

相關問題