我有这张桌子
topic_categories - >有很多 - > topic_sub_categories - >有很多 - > 主题 - >有很多 - > 问题 - >的选择
我想做什么来为每个topic_sub_categories提供10个随机问题给出topic_category_id
我已经使用SQL查询实现了
SELECT x.*
FROM (
SELECT ROW_NUMBER() OVER (PARTITION BY t.TopicSubCatId) AS rowNumber,
t.*
FROM (
SELECT abc.TopicSubCatId as TopicSubCatId, q.id as QuestionId, q.*
FROM questions q
LEFT JOIN topics t on t.id = q.topic_id
LEFT JOIN (SELECT tsc.id as TopicSubCatId
FROM topic_categories tc
LEFT JOIN topic_sub_categories tsc ON tc.id = tsc.topic_category_id
WHERE tsc.id IS NOT NULL
AND tc.id = 1
GROUP BY tsc.id, tsc.name) abc ON t.topic_sub_category_id = abc.TopicSubCatId
) t) x
where x.rowNumber <= 3
order by random()
问题是,我想热切地加载每个问题的选择
所以我的观点看起来像:
-@questions.each do |q|
q.choices.order("RANDOM()").each do |c|
end
end
你可以建议如何使用活动记录或任何其他方法来解决我的问题。
BTW:我正在使用postgresql