Ruby on Rails
HowToHandleMultipleRelationshipsBetweenTables

Say I am creating a task management application and I have two tables, users and tasks. There are many relationships between these tables:

Clearly the third relationship should be handled with a seperate table users_tasks and a has_and_belongs_to_many relationship in the Task and User models.

But how should the other relationships be handled? Wouldn’t they both want to be columns in tasks and named user_id? Is there a way to alias column names like created_by and completed_by so Rails knows to reference the User model?

Answer:
See the online documentation for those relationship methods that you put into the model files. They all have optional arguments (such as foreign_key? => “whatever”).
You can also define a more useful name for the relationship as well, using those arguments:

i would prefer this solution for bigger applications:

think about, you want to save activatiion of task, closure of task and so.

now you create join models

Activation and Closure which give you the possibility to save further information, like, when, why, how, categories etc. for this action.

(You could also do Single Table Inheritance on this Join Model, ask me if you don’t understand this)

Okay now you do the following:

every join model

belongs_to :user
belongs_to :task

And your User Model:

has_many :tasks, :through => :activation
has_many :tasks, :through => :closure

and your Task Model:

has_many :users, :through => :activation
has_many :users, :through => :closure

Now you’ve got User.tasks and of course User.closures etc.

You could also do this by polymorphic association.