Use a Custom Column Name With a belongs_to Association in Rails
Imagine an application with the following relationships:
- A
usermodel whichhas_manyjobsthrough ajobs_project_managersjoin table. - A
jobmodel whichhas_manyusersthrough ajobs_project_managersjoin table. - A
jobs_project_managermodel connecting thejobandusermodels.
Default Rails conventions would create a users method on a Job instance. However, there may be times when you want to customize the column name to be more expressive. In my case, I want a Job to have a project_managers method instead. This would still associate a job with a user model, but it reads better.
In order to achieve this, you’ll want to use the class_name and foreign_key options for the belongs_to method. Rails Guides provides an example of how to use these options. Essentially this allows you to create a custom name for the association, but tells Rails to refer to both the User class and the user_id column.