如何编写一个给出以下结果的查询:
https://stackoverflow.com/users/611696/hopstream?tab=tags
鉴于这些模型和关系:
User:
has_many: questions
has_many: answers
Questions:
belongs_to: user
has_and_belongs_to_many: tags
has_many: answers
Answers:
belongs_to: user
belongs_to: question
Tags:
has_and_belongs_to_many: questions
应该是在用户模型中,对吗?...
class User < MyModel
def topics
# get user's questions' topics
# get user's answers' questions' topics
# merge and remove duplicates
# sort by user's activity on topic (group by of questions and answers user has posted where the question had that tag)
end
end
或者有更简单的方法来实现这一目标吗?
答案 0 :(得分:1)
在我看来,任何形式的ORM都有助于根据一些(足够简单的)标准和遍历关联来检索记录。对于更复杂的报告这样的东西,不要犹豫使用纯SQL,它更适合这个。
下面是未经测试的,但应指向正确的方向:
class User < MyModel
def topics
connection.execute <<SQL
SELECT tag, count(*)
FROM questions_tags
WHERE question_id IN (
SELECT id
FROM questions
WHERE user_id = #{id}
UNION ALL
SELECT questions.id
FROM questions JOIN answers ON (question.id = answers.question_id)
WHERE answers.user_id = #{id}
)
GROUP BY tag;
SQL
end
end