The following code works for Postgres (Heroku):
@messages = Message.select("DISTINCT
ON (messages.conversation_id)
*").where("messages.sender_id = (?) OR messages.recipient_id = (?)",
current_user.id, current_user.id)
However, when attempting to order the results by appending .order("messages.read_at DESC") I receive the following error:
ActionView::Template::Error (PGError: ERROR: column id_list.alias_0 does not exist)
In looking at the generated SQL, I see that an alias is being created around the ORDER BY statement when not asked for:
messages.recipient_id = (32))) AS id_list ORDER BY id_list.alias_0 DESC)
I’ve not been able to figure out a workaround short of using “find_by_sql” for the entire statement – which takes a heavy toll on the app.
Don’t vote this, I only post because posting many lines in comments does not show very well.
I would write a “query that returns messages grouped by their conversation_id, so that the last message in each conversation is shown” like this:
No idea how this can be done in Heroku or if it even possible, but it avoids the
DISTINCT ON. If that’s causing the error, it may be of help.