Tuesday, April 20, 2010

Defining various roles via ActiveRecord Associations using Ruby on Rails

I have a User model. and I have a Project model.

Now a User could be associated with a Project in three ways,
* It could propose as project
* It could mentor a project
* It could be a student working on a project

I had added three foreign keys in my Project model,

t.integer "proposer_id"
t.integer "mentor_id"
t.integer "student_id"


Now how do I associate the three foreign keys with the User object?

Solution:

Add the following associations to your Project model:


belongs_to :proposer, :class_name => "User", :foreign_key => "proposer_id"
belongs_to :mentor, :class_name => "User", :foreign_key => "mentor_id"
belongs_to :student, :class_name => "User", :foreign_key => "student_id"


Now you can access your user from the Project instance like this:


@proposer = project.proposer
@mentor = project.mentor
@student = project.student


where project is an instance of Project model and proposer, mentor, student would be instances of the User model.




Foreign keys changed to match Rails conventions as proposed by Shakthi Kannan

Updates:

To access the assiciations from the User model, use the following associations:


has_many :project_proposals, :class_name => "Project", :foreign_key => 'proposer_id'
has_many :project_mentorships, :class_name => "Project", :foreign_key => 'mentor_id'
has_many :project_internships, :class_name => "Project", :foreign_key => 'student_id'


From your user model you can access the associations from your User instance like this:


@project_proposals = user.project_proposals
@project_mentorships = user.project_mentorships
@project_internships = user.project_internships



Posted from GScribble.

1 comment:

Anonymous said...
This comment has been removed by a blog administrator.