Ruby on rails 显示论坛列表中最后一个主题和用户的论坛架构
作为一个更大项目的一部分,我正在构建一个简单的论坛,其中一个要求是在公告板列表中,我们将显示最新的主题以及发布该主题的用户 以下是我拥有的相关模型:Ruby on rails 显示论坛列表中最后一个主题和用户的论坛架构,ruby-on-rails,Ruby On Rails,作为一个更大项目的一部分,我正在构建一个简单的论坛,其中一个要求是在公告板列表中,我们将显示最新的主题以及发布该主题的用户 以下是我拥有的相关模型: Board name description subjects_count has_many Subjects Subject title content user_id replies_count belongs_to Board belongs_to User has_many Replies R
Board
name
description
subjects_count
has_many Subjects
Subject
title
content
user_id
replies_count
belongs_to Board
belongs_to User
has_many Replies
Reply
content
belongs_to Subject
belongs_to User
User
name
has_many Subjects
has_many Replies
在boards index视图中,我为每个活动板显示了以下字段(可能有5-10个板):
要显示此信息,我现在使用以下方法:
def get_boards_and_latest_subject
Board.connection.select_all("SELECT boards.id, boards.name, boards.description, subjects.id as most_recent_subject_id, subjects.title as most_recent_subject_title, subjects.user_id, subjects.created_at, users.name as most_recent_subject_user_name, users.id as user_id, (select count(id) FROM subjects where board_id = boards.id) as subject_count
FROM boards
INNER JOIN (SELECT board_id, MAX(created_at) MaxDate FROM subjects s GROUP BY board_id) MAXDATES
ON boards.id = MaxDates.board_id
INNER JOIN subjects ON MaxDates.board_id = subjects.board_id AND MaxDates.MaxDate = subjects.created_at
JOIN users ON subjects.user_id = users.id")
end
我从我开始这个项目时使用的平台——CodeIgniter——带来了这个SQL,但现在对我来说似乎有点可笑。当时的目标是减少列出董事会时的查询数量
考虑到我拥有的板子数量(5-10个),做一些更像是在一个漂亮的AR调用中返回所有板子,并为每个板子获取最新的主题和用户,不是更好吗
或者,另一种选择是将最新的主题存储在boards表中,就像计数器缓存一样。由于计数器缓存的原因,当我添加主题时,我已经在更新表了,那么更新最后一个主题信息是否明智呢
我们现在正在重建的网站上的boards页面平均每月浏览量约为2万次,所以流量不大
def get_boards_and_latest_subject
Board.connection.select_all("SELECT boards.id, boards.name, boards.description, subjects.id as most_recent_subject_id, subjects.title as most_recent_subject_title, subjects.user_id, subjects.created_at, users.name as most_recent_subject_user_name, users.id as user_id, (select count(id) FROM subjects where board_id = boards.id) as subject_count
FROM boards
INNER JOIN (SELECT board_id, MAX(created_at) MaxDate FROM subjects s GROUP BY board_id) MAXDATES
ON boards.id = MaxDates.board_id
INNER JOIN subjects ON MaxDates.board_id = subjects.board_id AND MaxDates.MaxDate = subjects.created_at
JOIN users ON subjects.user_id = users.id")
end