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:
-
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
-
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=“syntaxhilite”>RUBY:-
class Project <ActiveRecord::Base
-
hasandbelongstomany :fund,
-
:classname => “Person”,
-
:jointable => “projectfund”
-
-
hasandbelongstomany :employee,
-
:classname => “Person”,
-
:jointable => “projectemp”
-
-
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:-
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
-
-
rendertext text