将Postgres查询转换为Rails ActiveRecord?

时间:2014-05-16 16:23:15

标签: ruby-on-rails ruby postgresql activerecord ruby-on-rails-4

是否可以使用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;

1 个答案:

答案 0 :(得分:0)

嗯,这应该有效。不完全相同但应该给出相同的结果。

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