neon
neon

Reputation: 2821

ORDER BY issue in Postgres (Heroku)

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.

Upvotes: 1

Views: 388

Answers (1)

ypercubeᵀᴹ
ypercubeᵀᴹ

Reputation: 115610

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:

SELECT m.*
FROM messages m
  JOIN 
    ( SELECT conversation_id
           , MAX(created_date) AS maxdate
      FROM messages
      WHERE ...
      GROUP BY conversation_id
    ) AS grp
    ON  grp.conversation_id = m.conversation_id
    AND grp.maxdate = m.created_date
ORDER BY m.read_at DESC

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.

Upvotes: 2

Related Questions