Create an array of objects ordered based on the attribute of the child class

I have a class Job

:

class Job < ActiveRecord::Base
  has_many :stops
end

      

Stop

class has attribute datetime :arrival time

What is a concise way to get an array of all jobs ordered by early arrival time at related stops?

eg.

If job_1 has two stops, one with an arrival time of 4pm and one with an arrival time of 5pm.

And job_2 has two stops, one with an arrival time of 3pm and one with an arrival time of 6pm.

I need array: [job_2, job_1]

I can achieve this, but in a cumbersome way that involves looping and temporarily storing values.

Thank!

+3


source to share


2 answers


Stop.all.order_by(arrival_time: :asc).select(:job).distinct

      



This will take all stops sorted by arrival time and then select only unique tasks. Make sure the Stop model has a job_to: job.

+2


source


That's a good question! Francesco will tell you where you are going, but if you prefer to use connections over sub-series, you have other options.

Job.includes(:stops).order('stops.arrival_time ASC')

      



Change includes

with joins

if you want to omit tasks that have no stops

+3


source







All Articles