将Postgres查询转换为Rails ActiveRecord?

是否可以用Rail的ActiveRecord格式编写以下查询? 我已经用arel尝试了十亿种不同的方式,但无法获得相同的结果。

SELECT topic_id, count(*) as total FROM questions_topics WHERE question_id IN ( SELECT id FROM questions WHERE user_id = 1000 UNION ALL SELECT questions.id FROM questions JOIN answers ON (questions.id = answers.question_id) WHERE answers.user_id = 1000 ) GROUP BY topic_id ORDER BY total DESC; 

嗯,这应该工作。 不完全相同的东西,但应该给出相同的结果。

 QuestionTopic.where( "question_id IN (?) OR question_id IN (?)", Question.where(user_id: 1000).select(:id), Answer.where(user_id: 1000).select(:question_id) ).group('topic_id') .order('total desc') .select('topic_id, count(*) as total')