Joining an attribute from a has_many through Table in Rails

52 views Asked by At

I have the following 2 models:

Parent Model:

  class Babysitter < ApplicationRecord

  has_many :jobs
  has_many :babysitters, through: :jobs

Babysitter Model:

  class Babysitter < ApplicationRecord

  has_many :jobs
  has_many :parents, through: :jobs

They have a has_many through relationship from the Job model:

Model Job:

    class Job < ApplicationRecord
      belongs_to :Babysitter, :touch => true
      belongs_to :Parent
    end

I now want to call babysitter.parents but have each parent also include the attribute salary (an attribute from the Jobs table).

Is this possible?

I tried:

babysitter.parents.includes(:jobs.salary)

Additionally is it possible to include the result in a fastJsonApi?

parents_including_salary = babysitter.parents.includes(:jobs.salary)

options = { include: [:babysitter, :'parents_including_salary']} json = Api::CampaignReportSerializer.new(otherData, options).serialized_json

1

There are 1 answers

0
imposterisasking On

I think you can use delegate to call the salary?

 belongs_to :Parent
 delegate :salary, to: :parent

you can try this

in your API can call parent.salary