Has and belongs to many
Mon, Dec 4, 2006
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:
-
class Person <ActiveRecord::Base
-
has_and_belongs_to_many :project
-
end
-
-
class Project <ActiveRecord::Base
-
has_and_belongs_to_many :person
-
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
-
person = Person.find (1) #Find person with id 1
-
#Render the name of the first project the person is in
-
render_text 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.
-
class Project <ActiveRecord::Base
-
has_and_belongs_to_many :fund,
-
:class_name => "Person",
-
:join_table => "project_fund"
-
-
has_and_belongs_to_many :employee,
-
:class_name => "Person",
-
:join_table => "project_emp"
-
-
end
A project now has funders and employees. The relations are stored in the database tables project_fund and project_emp. The table project_person is no longer needed.
-
project = Project.find (1) #Find person with id 1
-
#Render the name of the first person that funds this project
-
-
text = "First employee " +
-
project.employee[0].name +
-
" first funder " +
-
project.fund[0].name
-
-
render_text text
More documentation can be found on link
Popularity: 37% [?]

December 4th, 2006 at 9:11 pm
I posted 18 hours sooner with this http://www.nielsbruin.nl/blog/?p=73.
December 5th, 2006 at 11:26 am
Hi Niels, that’s true. But you didn’t described in detail how to create multiple relations between the same tables. This was a problem arno and i encountered.
December 5th, 2006 at 7:37 pm
I didn’t said it was the same, just coincidence thats these object come around now. My intention was to give some extra information.
December 5th, 2006 at 8:22 pm
object = subjects, to much as3