如何使用不同级别的连接表/模型构建数据库

时间:2015-05-17 13:10:06

标签: ruby-on-rails database data-structures

我正在构建一个存储宗教教科书的数据库。我的问题是每个文本都有不同的级别。

示例:

Bible -> Books -> Chapters -> Verses

Quran -> Chapters -> Verses

Pali Canon -> Books -> Sub_Books -> Chapters -> Sub_chapters -> Verses

我认为其他文本会有更多变化。构建这样的东西的最佳方法是什么,这样我的数据库和代码可以更灵活,并支持这些"子模型"

感谢。

用Ruby on Rails编写,所以任何适合的答案都会很棒。

1 个答案:

答案 0 :(得分:1)

使用self joins

可以非常简单地构建层次结构
books:
    id [integer, primary key, auto-index]
    parent_book_id: [integer, foreign-key self joins books]

chapters:
    id [integer, primary key, auto-index]
    book_id: [integer, foreign-key, joins books]
    parent_chapter_id: [integer, foreign-key self joins chapters] 

verses:
    id [integer, primary key, auto-index]
    chapter_id: [integer, foreign-key, joins chapters]
    parent_verse_id: [integer, foreign-key self joins verses] 

模特:

class Book < ActiveRecord::Base
    has_many :sub_books, class_name: "Book", foreign_key: "parent_book_id"
    belongs_to :parent_book, class_name: "book"
    has_many :chapters
    has_many :verses, though: :chapters
end

class Chapter < ActiveRecord::Base
    has_many :sub_chapters, class_name: "Chapter", foreign_key: "parent_chapter_id"
    belongs_to :parent_chapter, class_name: "Chapter"
    belongs_to :book
    has_many :verses
end

class Verse < ActiveRecord::Base
    has_many :sub_verses, class_name: "Verse", foreign_key: "parent_verse_id"
    belongs_to :parent_verse, class_name: "Verse"
    belongs_to :chapter
    belongs_to :book, though: :chapter
end