0

Here are my two models

class Customer
  field: name, type: String
  has_many :calls
end

class Call
  field: number, type: String
  field: call_time, type: DateTime
  belongs_to :customer
end

My requirement: For the above arrangement i.e., A Customer has_many Calls & a Call belongs_to a Customer. I would like to get the List of customers ordered by the latest call of their calls.

Let me explain. Say, the database has the following data

Customer
John
     Calls
     987     /  10AM
     987     /   9AM
Jack
     Calls
     878     /  11AM
     878    /    6AM
Rohan
     Calls
     990     /  9AM
     990    /   8AM

My expected output would be

Jack
John
Rohan

Since the latest call was from Jack (@11AM), then John (@10AM), then Rohan (@9AM). Now how do I write such a query?

1 Answer 1

0

As far as I understand, if the Call's are not embedded in the Customer document, the only solution is to load all of your customers and then sort them "manually" through Enumerable#sort, something like

Customers.where(some_criteria).sort_by { |c| c.calls.first.sort(call_time: -1) }

You might want to take a look at this: Mongoid, how to order_by through a references_one association (and subsequent associations)?

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.