2009-07-10 30 views
2

考慮到與他們的對應關係如下資源:Rails:多態性與否?

Site 
has_many :page 
has_many :groups 
has_many :projects 

Group 
belongs_to :site 
has_many :pages 

Project 
belongs_to :site 
has_many :pages 

是不是好,使頁面模型多態性或離開個別外鍵?

**Scenario 1 (Polymorphic)** 
Page 
pageable_id 
pageable_type 
title 
body 
.... 
.... 

**Scenario 2 (Non Polymorphic)** 
Page 
site_id (always filled) 
group_id (may be empty) 
project_id (may be empty) 
title 
body 
.... 
.... 

**Scenario 3 (Combination)** 
Page 
site_id 
pageable_id (may be empty, if page belongs only to site) 
pageable_type (may be empty, if page belongs only to site) 
title 
body 
..... 
..... 

哪上述3個場景,你會喜歡嗎?和爲什麼(在效率方面,等..)

注:如果頁面屬於:在我的意見,我會遍歷通過頁面來顯示相關鏈接(例如所有可能的關係我顯示回到組鏈接,...)

回答

0

我認爲在模型中包含site_id並不是一個好主意,因爲它可能會在屬於某個組的頁面的site_id不符合' t匹配該組的site_id。

這將離開只是場景1 ...

如果你想有做site.pages並得到所有屬於該網站的網頁(也屬於該網站屬於一組頁面的可能性),你可以ofcourse編寫自己的功能:

class Site 
    def all_pages 
    Page.find_by_sql(["SELECT p.* FROM pages p, sites s, groups g, projects j WHERE (p.pageable_type='Site' AND p.pageable_id=?) OR (p.pageable_type='Group' AND p.pageable_id=g.id AND g.site_id=?) OR (p.pageable_type='Project' AND p.pageable_id=j.id AND j.site_id=?, self.id, self.id, self.id]) 
    end 
end 

(另外,我會說出在這種情況下pageable_id列「PARENT_ID」和pageable_type「PARENT_TYPE」這似乎更符合邏輯,我...)

+0

我喜歡你選擇所有頁面的方法,但是它怎麼樣o中斷 - 「我認爲在模型中包含site_id並不是一個好主意,因爲當屬於某個組的頁面的site_id與該組的site_id不匹配時,它可能會中斷。」一個組必須在一個站點中,並且不能在一個站點之間進行更改。 – Dharam 2009-07-11 17:02:49