views:

75

answers:

1

I have an Order class that has_many :shipments. How can I use Order.find to return all the order objects whose newest shipment was created after a certain time (say, in the last hour)?

+2  A: 
Order.find(
  :all,
  :joins => :shipments, 
  :select => 'distinct orders.*', 
  :conditions => ['shipments.created_at > ?', Time.now - 1.hour])

The :joins ensures that you get orders that have shipments and the :conditions ensures that you only get shipments created in the last hour.

The :select means you only get one instance of each order in case an order has multiple notifications in the last hour.

I'm not sure the 'newest' stipulation is important as, if any shipment has been created in the last hour then the newest shipment will also match that condition.

Shadwell
"I'm not sure the 'newest' stipulation is important as, if any shipment has been created in the last hour then the newest shipment will also match that condition." -- Answer: I am an idiot.
Horace Loeb