Get data with belongs to relations

Viewed 48

I have relation between three tables: CarChangeDetail - CarChangeDetail belongs to CarChange - CarChange belongs to ReasonToChangeCar

now I have id thats fit's the first table one of the keys

I managed to this in three queries and i want to make it in one:

const id = 6;

  carChangeDetails = CarChangeDetail.where(car_id: id).last.as_json
  carChangeId = CarChange.where(id:carChangeDetails['car_change_id']).pluck(:reason_to_change_car_id).first
  carChangeDetails['reason'] = ReasonToChangeCar.where(id:carToChangeId).pluck(:reason).first

tried joins but with no luck. please advise :)

0 Answers
Related