Tom Lehman
Tom Lehman

Reputation: 89203

Find all objects that have an associated object with a certain property

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)?

Upvotes: 0

Views: 152

Answers (1)

Shadwell
Shadwell

Reputation: 34774

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.

Upvotes: 2

Related Questions