2010-12-10 50 views
0

我建立使用DataMapper的西納特拉和小Ruby應用程序,我試圖定義一個基本的博客模式:DataMapper的子類和許多一對多的自我指涉的關係

  • 的博客有多個用戶
  • 我文章的集合,其中的每一個由用戶發佈
  • 每個崗位都有一組評論
  • 每個註釋都可以有它自己的一套評論 - 這可以重複了好幾層深

由於每條評論belongs_to一個帖子,我遇到了麻煩得到評論之間的自我參照關係。我的班,現在這個樣子:

class User 
    include DataMapper::Resource 
    property :id, Serial 
    property :username, String 
    property :password, String 

    has n, :post 
end
class Post 
    include DataMapper::Resource 
    property :id, Serial 
    property :content, Text 

    belongs_to :user 

    has n, :comment 
end
class Comment 
    include DataMapper::Resource 
    property :id, Serial 
    property :content, Text 

    belongs_to :user 
    belongs_to :post 
end

我在之後的Associations指導,建立一個新的對象(CommentConnection)鏈接兩個評論在一起,但我的問題是,每個subcomment不應該像評論類所暗示的那樣屬於郵政。

我的第一本能是爲評論提取一個超類,以便一個子類可以是「頂級」並屬於一個帖子,而另一種類型的評論屬於另一個評論。不幸的是,當我這樣做時,我遇到了註釋ID變爲空的問題。

在DataMapper中建立這種遞歸評論關係的最佳方式是什麼?

回答

5

您需要的是自我參照連接的評論,例如,每個評論可以有一個家長評論。請嘗試以下操作:

class Comment 
    include DataMapper::Resource 
    property :id, Serial 
    property :content, Text 

    has n, :replies, :child_key => [ :original_id ] 
    belongs_to :original, self, :required => false #Top level comments have none. 
    belongs_to :user 
    belongs_to :post 
end 

這將讓你有答覆任何評論,但訪問它們可能會變得有點討厭(慢),如果音量變高。如果你得到這個工作,並想要更復雜的東西,你可以看看嵌套集,我相信有DataMapper的嵌套集插件,但我沒有使用。

+1

剛開始測試這個,它工作得很好 - 謝謝! – Tim 2011-02-24 00:26:16