Order by child

Hello,

I have a Product model with a has_many relationship towards a Order
model. What i am trying to get is a list of all products, ordered by the
most recent Order.

For example:

Product “Old Book” was last sold on 11 November
Product “Camera Bag” was last sold on 14 November

“Old book” will be the first in the list and “Camera Bag” the second.

Regards,

Vincent

Vincent B. wrote:

Hello,

I have a Product model with a has_many relationship towards a Order
model. What i am trying to get is a list of all products, ordered by the
most recent Order.

For example:

Product “Old Book” was last sold on 11 November
Product “Camera Bag” was last sold on 14 November

“Old book” will be the first in the list and “Camera Bag” the second.

Join the tables and use an appropriate order clause.

Regards,

Vincent

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

I also want the products without an order. Wouldn’t that leave them out?

[Please quote when replying. It makes the discussion easier to follow.]

Vincent B. wrote:

I also want the products without an order. Wouldn’t that leave them out?

Not if you use a left outer join.

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

Vincent B. wrote:

Hello,

I have a Product model with a has_many relationship towards a Order
model. What i am trying to get is a list of all products, ordered by the
most recent Order.

For example:

Product “Old Book” was last sold on 11 November
Product “Camera Bag” was last sold on 14 November

“Old book” will be the first in the list and “Camera Bag” the second.

Regards,

Vincent

For anyone trying to find the end result. This is what I came up with

@products = Product.find(:all, :joins => "LEFT OUTER JOIN orders u ON
u.product_id = products.id ", :order => “u.created_at DESC”, :group =>
“products.id”)