views:

111

answers:

2

So I'm teaching myself Ruby on Rails, with a PHP background. I've written a sloppy, proof-of-concept PHP application called "2NDP." I want to re-create this in Ruby on Rails (but more basic, more clean, and with a better interface), so I can learn some of the basics.

2NDP is a website where you can basically write your own "Choose-Your-Own-Adventure" books, but collaboratively, with other people. The way I made this work with PHP/MySQL is, I had a table of stories and a table of pages. The pages would belong to stories (obviously), but each page would have references to up to four other pages by having four separate columns, one for each possible page ID that could be referenced.

So right now in my RoR application, I have "stories" that have "pages" that are associated with them. I need a way to get the pages to reference each other, but the possibility of more than one reference per page (one page may reference up to four other pages).

I really like the "references" thing that RoR has, but is there any way to gracefully implement this sort of system? Keep in mind that my only RoR experience is walking through four tutorials, and I'm trying to re-apply what I've learned with a "real-life application."

+1  A: 

Rather then having four seperate columns, a separate joining table might be more appropriate. For example:

Pages -> LinkedPages -> Pages

Then you can create a has_many through relationship.

class Pages < ActiveRecord::Base
  has_many :linked_pages
  has_many :pages, :through => :linked_pages
end

class LinkedPages < ActiveRecord::Base
  belongs_to :pages, :class_name => "Pages", :foreign_key => "page_id"
  belongs_to :linked_pages, :class_name => "Pages", :foreign_key => "linked_id" 
end

Then when using your Page object you can simply say:

my_page.pages
Hates_
Thank you! I'm still getting used to this RoR mentality, and this seems like a very good and logical solution.
Unniloct
A: 

Hates_, that was helpful, but if anyone needs a more in-depth explanation about this sort of thing, read about it here.

Unniloct