2010-06-12 101 views
1

我的需求非常簡單:我有一個提示表來接收評論並且有評論也可以收到評論。導軌:自我指涉協會

要檢索存儲在同一個表(評論)中的每條評論,我爲評論創建了另一個關鍵字:「inverse_comments」。

我試圖通過使用自引用關聯來使用一個評論表。有些資源似乎將不止一張表納入與我的需求不同的表格中。於是我想出了whth以下建模徵求意見:

class Comment < ActiveRecord::Base 
    belongs_to :tip 
    belongs_to :user 
    has_many :mycomments, 
      :through => :inverse_comments, 
      :source => :comment 
end 

顯然缺少的東西在這裏,但我無法弄清楚。 有人能對此有所啓發:

我需要做些什麼才能使模型發揮作用?

謝謝。

回答

5

我相信你應該使用polymorphic association

爲此,您需要在comments表中添加commentable_idcommentable_type。和你的模型應該是這樣的:

class Comment < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :commentable, :polymorphic => true  
    has_many :comments, :as => :commentable 
end 

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

這樣,您就可以使用

@tip.comments 
@comment.comments