Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails has_many :through with different column name in association table

I currently have two different models: User and Project. The User model has three types of users - owners, contractors and clients. I want to assign multiple contractors to one project. I am trying this with a has_many :through association, like so:

Class User
   has_many :assignments
   has_many :projects, :through => :assignments 

Class Project
   has_many :assignments
   has_many :contractors, :through => :assignments

Class Assignment
   belongs_to :user
   belongs_to :project

My issue is in using contractor_id in the assignments table instead of user_id.

In my assignments table I currently have columns contractor_id and project_id. Everything seems to work if I use user_id instead, but that will cause things to be pretty messy later on in my views.

How would I accomplish this?

like image 393
Andy Bas Avatar asked Jun 15 '12 18:06

Andy Bas


1 Answers

You should use the :foreign_key option in Assignment, e.g.:

class Assignment
  belongs_to :user, :foreign_key => :contractor_id
  belongs_to :project
like image 118
Jordan Running Avatar answered Oct 27 '22 06:10

Jordan Running