如何建模多博客网站?

Jim*_*nes 2 database-design ruby-on-rails

我有这些表:

**Sites**
:has_many :blogs
:has_many :pages

**Blogs**
:belongs_to :site

**Pages**
:belongs_to :site
:belongs_to :blog
Run Code Online (Sandbox Code Playgroud)

基本上,我希望能够创建与站点相关的页面或与博客相关的页面,其中包含以下路由:

/blogs/1/pages/1
/sites/1/pages/2 
Run Code Online (Sandbox Code Playgroud)

使用我当前的设置,我的Pages表有一个blog_id和site_id的foreign_key - 我只是想这样做:

  • 如果正在为网站创建页面(意味着它不属于博客),则将blog_id =设置为NULL,但相应地设置site_id

  • 但是,如果正在为博客(已经属于某个站点)创建页面,则设置相关的site_id和blog_id

然后,如果我想要一个站点页面列表:我可以只查询Pages表中的所有NULL blog_ids,如果我想要Blog页面,我将通过与Blog的关系来获取它们.

更新:我接受了下面建议使用"多态关联"的答案,但这也可以使用单表继承吗?如果是这样,哪种方法更好?

谢谢.

mol*_*olf 5

您可以使用多态关联.

pages表中添加外键和类型列.找到一个形容词,描述您的网页可以属于的类的公共属性.我想出了pageable(给了我一个pageable_idpageable_type专栏).如果您使用迁移,请添加以下Page迁移:

# Adds "pageable_id" integer column and "pageable_type" string column.
t.references(:pageable, :polymorphic => true)
Run Code Online (Sandbox Code Playgroud)

在模型中,使用has_many/ 时指定多态关系belongs_to:

class Site < ActiveRecord::Base
  has_many :pages, :as => :pageable
end

class Blog < ActiveRecord::Base
  has_many :pages, :as => :pageable
end

class Page < ActiveRecord::Base
  belongs_to :pageable, :polymorphic => true
end
Run Code Online (Sandbox Code Playgroud)

看哪:

# Return all pages belonging to Site with ID 12, that is, return all pages
# with pageable_id 12 and pageable_type "site".
Site.find(12).pages

# Return all pages belonging to Blog with ID 3, that is, return all pages
# with pageable_id 3 and pageable_type "blog".
Blog.find(3).pages

# Returns the owner (Blog or Site) of Page with ID 27.
Page.find(27).pageable
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助.