I've searched a lot here but couldn't find a similar topic: i need to write a Query in Arel because i use will_paginate to browse through the results, so i'd loose much comfort in implementation with raw SQL.
Here's what i need to spell in Arel:
SELECT m.*
FROM messages m
JOIN (SELECT tmp.original_id as original_id,
max(tmp.id) as id
FROM messages tmp
WHERE tmp.recipient_id = ?
GROUP BY tmp.original_id) g ON (m.id = g.id)
ORDER BY m.updated_at DESC;
Explained in short words: the subquery retrieves all messages for a user. If a message has newer replies (in replies i save the refering message id as original_id) the older ones will be ignored. For the result of all these messages i want Rails to deliver me the correpsonding objects.
I'm quite skilled in SQL but unfortunately not with Arel. Any help would be kindly appreciated.