0

我的情景是,有幾種不同的模型可以有評論。試圖找出關係:評論belongs_to其中幾個模型

Post 
    has_many :comments 

Update 
    has_many :comments 

Comment 
    belongs_to EITHER :post OR :update (but not both)???? 

什麼是建立評論關係的正確方法?我希望能夠調用Post.commentsUpdate.comments

回答

5

聞起來像一個polymorphic association

隨着多態關聯,模型可以屬於一個以上的其他模式,在單一的關聯。例如,您可能有一個屬於員工模型或產品模型的圖片模型。

所以,你會想是這樣的:

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

class Post < ActiveRecord::Base 
    has_many :comments, :as => :commentable 
end 

class Update < ActiveRecord::Base 
    has_many :comments, :as => :commentable 
end 

你不得不建立在數據庫中的幾件事情對這項工作爲好。有關您需要的列的詳細信息,請參閱Active Record Associations GuidePolymorphic Associations部分。

+1

+1像往常一樣:-)謝謝你鏈接到費曼系列順便說一句! – Tilo

+0

@Tilo:謝謝,RPF是我的英雄,[Sagan系列](http://www.youtube.com/watch?v=oY59wZdCDo0)也值得一試。 –

+0

斑點 - 正是它看起來像什麼多態性創建 – brittohalloran