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:
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: