为活动记录编写复杂查询

时间:2015-10-17 20:54:15

标签: ruby-on-rails

@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')

我怎么写呢?

1 个答案:

答案 0 :(得分:1)

使用有效记录语法无法做到这一点 我只能建议你使用Arel gem(https://github.com/rails/arel)来构建比纯sql-string更优雅的sql-query

相关问题