I am trying to order some values that I get back from a query. The scope is as follows: 

`scope :complete, -> {where(status:[Status::SOLD, Status::NO_SALE])}`

In an API I return `a.items.complete` which is call the above query. I need to modify this call by adding an `order` clause based on two attributes: `starts_at` and `scheduled_end_time` in descending order. So I tried the following but and getting an error:

`items = items.complete.order("CASE WHEN items.actual_end_time IS NULL THEN items.starts_at ELSE items.scheduled_end_time END DESC")`

**ERROR:**
`{"error":"Mysql2::Error: Unknown column 'items.starts_at' in 'order clause': SELECT `items`.* FROM `items` WHERE `items`.`company_id` = 2 AND `items`.`status` IN ('sold', 'no_sale') ORDER BY CASE WHEN scheduled_end_time IS NULL THEN starts_at ELSE scheduled_end_time END DESC LIMIT 25 OFFSET 0"}`

I am trying to determine how to check if scheduled\_end\_time is null and if so order by the starts\_at...If I strip of the DESC at the end it works, but I need them to be descending. Any help or pointers is appreciated.

Auctions have many Items for what its worth.

**Auctions schema:**

[![enter image description here](https://i.stack.imgur.com/lPadX.png)](https://i.stack.imgur.com/lPadX.png)

**Items schema:**

[![enter image description here](https://i.stack.imgur.com/nuoz9.png)](https://i.stack.imgur.com/nuoz9.png)