This feels so much harder than I think it should!
I have a Rails model: MarketplaceMessage
Every message has an initial_record_id - if it's the first message, it's the ID of the record and if it's a reply it is the first record in the thread.
I want to show the distinct threads, ordered by the most recent message in the threads descending - so:
- Message id: 12, initial_record_id: 3
- Message id: 11, initial_record_id: 4
- Message id: 10, initial_record_id: 10
If it wasn't distinct, it would just be order(id: :desc) - but that returns multiple messages from the thread.
This mostly works - it returns the most recent messages from each thread - but the returned messages are ordered asc:
scope :distinct_threads, -> {
select("DISTINCT ON (marketplace_messages.initial_record_id) *")
.order("marketplace_messages.initial_record_id, marketplace_messages.id desc")
}
How do I get this to work and avoid the error:
ActiveRecord::StatementInvalid:
PG::InvalidColumnReference: ERROR: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
I assume I have to use some sql, but would prefer to do it as Railsy as possible