0

I have 2 models: Journal and Page. I have a couple of things I want to be able to do with this association.

  1. I want to be able to have a MainPage have many Subpages like a Chapter.

  2. I want to be able to move the MainPage and Subpages or just a single Page over to a different Journal.

  3. I want to be able to turn a MainPage into a Subpage and vice versa.

Here's my models so far:

class Page < ActiveRecord::Base
  belongs_to :user
  belongs_to :journal
end


class Journal < ActiveRecord::Base
  belongs_to :user
  has_many :pages
end

How would I go about doing the 3 above?

user2784630
  • 796
  • 1
  • 8
  • 19

1 Answers1

1

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.

Community
  • 1
  • 1
Enermis
  • 679
  • 1
  • 5
  • 16