写活动记录的复杂查询

问题描述:

@conversations = Message.find_by_sql("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") 

我有这个查询,这对我来说有点复杂,作为初学者。我一直试图根据活动记录来写这个查询,但是我不能。写活动记录的复杂查询

我有这个查询,但这是不正确的。

@conversations = Message.where('recipient_id = ?', current_user.id).select('sender_id AS correspondent') + Message.where('sender_id = ?', current_user.id).select('recipient_id AS correspondent') 

我该怎么写呢?

你不能使用活动记录语法。
我只能建议你使用Arel gem(​​)来建立sql-query比纯sql字符串更优雅