Ruby on Rails
TutorialBasicRelational

« TutorialStepSix | Tutorial | TutorialScaffolding »

So far we’ve seen how to access a single table, but what happens on a more complex relationship? What about phone numbers in our example?

Since cell phones have moved from a novelty to a requirement, most of us techs have several phone numbers. (I’m assuming the reader is familiar with relational database design… if not, please study it elsewhere quickly!)

Let’s add another table to our database.

If you’re using mysql run the following SQL code:

CREATE TABLE `phones` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `person_id` int(10) unsigned NOT NULL default '0',
  `phone` varchar(15) NOT NULL default '',
  PRIMARY KEY  (`id`),
  KEY `people_id` (`person_id`),
  KEY `phone` (`phone`)
) TYPE=MyISAM;
INSERT INTO `phones` VALUES (1, 1, '1234567890');
INSERT INTO `phones` VALUES (2, 1, '1122334455');

Or for postgresql:

CREATE TABLE phones (
    id serial PRIMARY KEY, 
    person_id int  NOT NULL, 
    phone text, 
    FOREIGN KEY (person_id) REFERENCES people ON DELETE CASCADE);

INSERT INTO phones (person_id, phone) VALUES (1, '1234567890');
INSERT INTO phones (person_id, phone) VALUES (1, '1122334455');

Or for SQLite:

CREATE TABLE phones (
  id          INTEGER PRIMARY KEY,
  person_id   INTEGER NOT NULL,
  phone       TEXT,
  FOREIGN KEY (person_id) REFERENCES people ON DELETE CASCADE
);

INSERT INTO phones (person_id, phone) VALUES(1, '1234567890');
INSERT INTO phones (person_id, phone) VALUES(1, '1122334455');

Important semantics to note: by default the foreign key is the name of the foreign table plus _id, ie, person_id. Also, note that the table name is a plural, while the model is singular. Let’s define it now:

./script/generate model Phone

A new file, phone.rb, will have been created in the model directory. You will want to change it so that it looks like:

class Phone < ActiveRecord::Base
   belongs_to :person
end

In the person.rb file, however, add a line to make it look like this:


class Person < ActiveRecord::Base
    has_many :phones
end

By calling has_many as we have, ActiveRecord now knows about the relation. Displaying it on our page is easy.

In the “view” view, add the following lines somewhere:

<% for phone in @person.phones %>
<%= phone.phone %><br/>
<% end %>

Now we have multiple phone numbers for this Person.

Go on to TutorialScaffolding | Tutorial | Back TutorialStepSix

category:Tutorial