0

Is there a cleaner way of associating a has_one...through relationship if the original object can have one and only one relationship through a couple of different objects (i.e. in the example below, they will only have 1 job but it may be through any of the available options)?

Toy example:

class Person
  belongs_to :employer
  belongs_to :consulting_agency
  belongs_to :temp_agency

  has_one :job, through: :employer
  has_one :job, through: :consulting_agency
  has_one :job, through: :temp_agency

Can this be consolidated or cleaned up in any way?

4
  • You might want to rethink your data model or you are going to have even more complicated problems down the road. Commented Dec 4, 2024 at 15:15
  • I agree with @dbugger but also worth noting that under your current proposal the only job relationship that would exist is the has_one :job, through: :temp_agency because this will overwrite the through: :consulting_agency which will have overwritten the through: :employer Commented Dec 4, 2024 at 15:19
  • @engineersmnky Thanks, good point. So a better option may be to remove the has_ones and create a job_lookup-type of method? This would forego the implied associations. def job; self.employer&.job || self.consulting_agency&.job || self.temp_agency&.job; end Commented Dec 4, 2024 at 15:24
  • 1
    @JacobMiller a better solution would probably be to have the Job belong to one of those parties (maybe as a polymorph) and then have the Person have has_one :job and has_one :employer, through: :job Commented Dec 4, 2024 at 15:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.