在Rails中的典型用户 - 帖子 - 评论模型中,每个用户都可以创建帖子并且还可以创建评论,问题是如何抓住每个用户对特定帖子的最新评论。
Example:
Post A have 3 user making comment
User 1 have comment 1, 2, 3, 4, 5, 6
User 2 have comment 1, 2, 3, 4
User 3 have comment 1, 2
所以我想要的视图只是每个用户的最新评论:
Post A have 3 user making comment
User 1 latest comment that is 6
User 2 latest comment that is 4
user 3 latest comment that is 2
怎么做?
感谢
答案 0 :(得分:1)
这样的事情:
post.comments.for_user(current_user).last
在模型中添加named_scope
class Comment
named_scope :for_user, lambda{ |user| {:conditions=>{:user_id => user.id}}
end
这应该可以解决问题。
如果你宁愿在rails中这样做,
messages_by_users = post.messages.group_by(&:user)
messages_by_users.each do |key, value|
messages_by_users[key] = value.last
end
答案 1 :(得分:0)
我必须得到这种数据,通常我最终会做两个查询。在我的情况下,我有博客和他们的帖子,我想要一个最近3篇博客文章的列表,限制博客是独一无二的,我不想要来自同一博客的2个帖子。我最终做了这样的事情(MySQL):
q = <<-EOQ
SELECT id,pub_date FROM
(
SELECT id,blog_id,pub_date
FROM posts
ORDER BY pub_date DESC
LIMIT 40
)
t
GROUP BY blog_id
ORDER BY pub_date DESC
LIMIT #{num_posts}
EOQ
post_ids = Post.connection.select_values(q)
Post.find(:all, :include => [:blog], :conditions => ["id IN (?)", post_ids], :order => "posts.pub_date DESC")
所以在你的情况下,你可能有类似的东西:
q = <<-EOQ
SELECT id FROM
(
SELECT id,post_id
FROM comments
ORDER BY id DESC
LIMIT 40
)
t
GROUP BY post_id
ORDER BY id DESC
LIMIT 10
EOQ
post_ids = Post.connection.select_values(q)
Post.find(:all, :include => [:blog], :conditions => ["id IN (?)", post_ids], :order => "posts.id DESC")
答案 2 :(得分:0)
假设您的数据库正在为评论分配顺序ID,您可以这样做:
class Comment
named_scope :most_recent, lambda {
lastest_comments = Comment.maximum :id, :group => "user_id, post_id"
{ :conditions => [ "comment_id in ?", lastest_comments.map(&:last) ] }
}
end
这为您提供了一种双查询方法,您可以通过各种方式使用它。上面的named_scope
会为所有帖子上的所有用户提取最新评论。如果您的数据库很庞大,这可能会成为一个问题,但您当然可以添加条件以使其更具体。
目前,这是一种灵活的方法,可以让您执行以下操作:
Comment.most_recent.find_by_user @user #-> the most recent comments on all posts by a user
@user.comments.most_recent #-> same as above
Comment.most_recent.find_by_post @post #-> the most recent comments on a single post by all users
@post.comments.most_recent #-> same as above
Comment.most_recent.find_by_user_and_post @user, @post #-> the specific most recent comment by a certain user on a certain post
@post.comments.most_recent.find_by_user @user #-> you get the idea