1

Is it possible to write the following query in Rail's ActiveRecord format? I've tried a billion different ways with arel but can't get the same results.

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;
5
  • Do you have relevant models like QuestionTopic and others? Commented May 16, 2014 at 16:42
  • 1
    I'd start by converting it to EXISTS (...) OR EXISTS (...) form, which will probably be more efficient than a UNION. Commented May 16, 2014 at 16:49
  • Maybe this talk will help you understand Arel: youtube.com/watch?v=ShPAxNcLm3o It explains how to convert any SQL query to Arel AST Commented May 16, 2014 at 19:23
  • Why do you want to convert it? One piece of SQL will probably be a lot clearer than an incomprehensible mess of Arel calls. Commented May 17, 2014 at 0:37
  • @muistooshort Since using Arel could allow rails to utilize lazy loading. I might be incorrect. Commented May 17, 2014 at 0:42

1 Answer 1

2

Well, this should work. Not exactly the same thing but should give same results.

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.