0

I've got a rather weird case. I have a few models that are tied together via associations one of these associations allows the user model to access referenced job data directly with the job model. However, the second case allows the user model to access the job data via the locations model.

User has_and_belongs_to_many :jobs
User has_many :jobs through: :locations

So how do I need to distinguish these two lines of code so that User.jobs uses the first association and User.jobs_through_locations uses the second association?

Cannon Moyer
  • 3,014
  • 3
  • 31
  • 75
  • Is [this](https://stackoverflow.com/questions/1163032/rails-has-many-with-alias-name) what you're looking for? – wolfson Mar 08 '18 at 22:01
  • @wolfson I tried that but couldn't get it to work most likely because of the many-to-many association. I would think something like that would work though. – Cannon Moyer Mar 08 '18 at 22:03

2 Answers2

0

If Locations has many jobs, give the second association a different name and tell it which association in Location is the source.

User has_many :jobs_through_locations, through: :locations, source: 
:jobs
JohnsWort
  • 118
  • 7
0

Use custom association name for the second association and use that name for referencing the jobs from third table.

Note: source is important as you need to tell rails which model to use when fetching user_jobs.

User

has_and_belongs_to_many :jobs

has_many :user_jobs, through: :locations, :source => :jobs

Rohan
  • 2,681
  • 1
  • 12
  • 18