to satisfy requirement 1 you'd need a self reference from pages to pages. this problem is already answered here
You'd do something like this
class Page < ActiveRecord::Base
belongs_to :user
belong_journal
has_many :pageRelations, :foreign_key => "page_id", :class_name => "PageRelation"
has_many :pages, :through => :pageRelations
def addSubPage(page)
# TODO: put in check that association does not exist
self.pages << page
page.pages << self
end
end
class PageRelation < ActiveRecord::Base
belongs_to :parentPage, :foreign_key => "page_id", :class_name => "Page"
belongs_to :subPage, :foreign_key => "page_id", :class_name => "Page"
end
requirement 2 will be trivial since you already stored the foreign key to the journal
page = Page.new
page.journal= Journal.new
for requirement 3 you have 2 aspects.
1 turning a main page into a subpage
this is simply adding it in a relation to another page
sPage = Page.new
pPage = Page.new
pPage.addSubPage(sPage)
for the second aspect you'd need to remove the page from all the relations where it is a subPage.
You will probably also want to do some bookkeeping to flag wether or not a page is a subpage or a root page.