2009-08-27 63 views
0

在Rails中的典型User - Post - Comment模型中,每個用戶都可以創建一個Post並且還可以創建Comment,問題是如何抓住每個用戶對特定帖子的最新評論。只抓取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

所以當張貼有3個用戶,你說,郵政模型的has_many用戶,或者說,它的has_many評論而這又屬於用戶? – Matchu 2009-08-27 00:28:55

+0

用戶有很多帖子和評論,帖子有很多評論和屬於用戶,評論屬於帖子,屬於用戶 – gkrdvl 2009-08-27 00:30:21

回答

1

事情是這樣的:

post.comments.for_user(current_user).last 

在模型

class Comment 
    named_scope :for_user, lambda{ |user| {:conditions=>{:user_id => user.id}} 
end 

這應該做的伎倆添加named_scope。

如果你寧願做它的軌道,

messages_by_users = post.messages.group_by(&:user) 

messages_by_users.each do |key, value| 
    messages_by_users[key] = value.last 
end 
+0

我想知道是否有一個單一的查詢方式來完成這項工作,如果你想顯示最新的評論所有3個用戶... – Matchu 2009-08-27 00:34:26

+0

Matchu,我添加了一個rails解決方案來加載查詢只有一次 - 通過加載所有評論到內存中),我不知道是否有其他更好的方法使用SQL – 2009-08-27 01:01:42

+0

@ez,第一個解決方案只抓住current_user最新評論,如何抓住另一個? – gkrdvl 2009-08-27 01:19:29

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") 
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