Has and belongs to many

The has_many_and_belongs_to_many relation is a very powerful construct in Ruby to set a relation between two entities. You can use this for many to many relations. For instance the relation between a person and a project.
A person works in many projects, and a project can have many persons working on it. Typically this will lead to three tables:

  • Person table (id, name, etc.)
  • Project table (id, name, etc)
  • Person_project table (person_id, project_id) storing the relation between a project and a person

In Ruby on rails you will have two classes in your model:

RUBY:
  1. class Person <ActiveRecord::Base
  2.    has_and_belongs_to_many :project
  3. end
  4.  
  5. class Project <ActiveRecord::Base
  6.    has_and_belongs_to_many :person
  7. end

By creating these relations rails creates some properties for you. One of the properties created in the Person class is the property project. You can do the following

RUBY:
  1. person = Person.find (1) #Find person with id 1
  2. #Render the name of the first project the person is in
  3. rendertext person.project[0].name

This is all great. But what if there are multiple relations between person and project. One relation between project and person may be that a certain person works in a project. Another relation could be that a number of persons fund a project. We need to enhance the relation between Person and project.

<div class=“syntax
hilite”>RUBY:
  1. class Project <ActiveRecord::Base
  2.    hasandbelongstomany :fund,
  3.       :classname => “Person”,
  4.       :jointable => “projectfund”
  5.    
  6.    hasandbelongstomany :employee,
  7.       :classname => “Person”,
  8.       :jointable => “projectemp”
  9.  
  10. end

A project now has funders and employees. The relations are stored in the database tables projectfund and projectemp. The table projectperson is no longer needed.

<div class=“syntaxhilite”>RUBY:
  1. project = Project.find (1) #Find person with id 1
  2. #Render the name of the first person that funds this project
  3.  
  4. text = “First employee ” +
  5.    project.employee[0].name  +
  6.    “ first funder ” +
  7.    project.fund[0].name
  8.  
  9. rendertext text

More documentation can be found on <a href=“http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html#M000533” onclick=“javascript:urchinTracker(‘/outbound/api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.htmlM000533’);”>link