Wednesday, February 3, 2010

Getting data with has_many and belongs_to associations

Projects Table
id Integer Auto-incrementing field
title Varchar(255)
description text

Tasks Table
id Integer Auto-incrementing field
name Varchar(255)
comment text
project_id Integer #This tells which project a task belongs to. This field is named following a Rails convention and refers to a related row in the projects table. This is called a foreign key and is more than just a device to help a programmer remember table and object relationships.

Project Model (project.rb)

has_many :tasks

Task Model (task.rb)

belongs_to :project

For instance, from the relationships defined in the models each task has a project title that can be accessed by task.project.title and each project has a list of tasks accessed by project.tasks.

An example shows the ease of finding all the tasks for a specific project.

def show
project = Projects.find(params[:id])
tasks = project.tasks.find(:all)

This example is similar to the list action above. The "1" in the URL below is where params[:id] comes from.