如何在邮件系统中列出对话

时间:2015-10-17 01:06:02

标签: mysql ruby-on-rails

我现在更新了整个问题。

我有用于存储用户消息的消息表。通过使用此表,我能够向用户列出消息,但我也试图在消息的左侧列出对话,就像Facebook一样。

我找出了必要的查询:

"SELECT correspondent, MAX(updated_at) as date FROM (SELECT sender_id as correspondent,updated_at FROM messages WHERE recipient_id = #{current_user.id} UNION ALL SELECT recipient_id as correspondent, updated_at FROM messages WHERE sender_id = #{current_user.id}) x GROUP BY correspondent ORDER BY date desc"

问题是我使用find_by_sql()函数来检索数据。我现在的问题是,如何根据Active Record编写此查询?

1 个答案:

答案 0 :(得分:0)

由于您已经获得了SQL查询,为什么不执行该查询以获得预期结果?

sql_query = "SELECT correspondent, MAX(updated_at) as date FROM (SELECT sender_id as correspondent,updated_at FROM messages WHERE recipient_id = #{current_user.id} UNION ALL SELECT recipient_id as correspondent, updated_at FROM messages WHERE sender_id = #{current_user.id}) x GROUP BY correspondent ORDER BY date desc"
results = ActiveRecord::Base.connection.execute(sql_query)
# use results e.g. loop through them in your program

然后,您可以根据自己的意愿在Rails应用中使用results