2012-01-20 44 views
1

我有3個表格:組,用戶和帖子。帖子有一個user_id,用戶有一個group_id。我想知道哪個組具有日期範圍內的頂級海報,最好只使用ActiveRecord。我認爲這個查詢做的工作:有沒有辦法將其轉換爲rails arel查詢?或者更好的方式來做這個查詢?

select g_id, count(p_id) as posts_count 
from (
    select users.group_id as g_id, posts.id as p_id 
    from users inner join posts 
    on users.id = posts.user_id 
    where users.group_id is not null 
    and posts.created_at > :since 
    and posts.created_at <= :until 
) as foo 
group by g_id 
order by posts_count desc limit 1; 

有人可以幫我翻譯它爲紅寶石?

回答

2

它可以在幾個步驟中完成。 首先 - 獲得由group_id分組的帖子數量。

posts = Post.includes(
     :user 
    ).where(
     'users.group_id is not null' 
    ).where(
     :posts => {:created_at => ('12.09.2011'.to_date)..('12.09.2012'.to_date)} 
    ).group(
     :group_id 
    ).count 

它會返回一個哈希像{1=>4, 2=>5, 3=>2},其中關鍵的是組的ID和值職位數。

然後你需要對這個散列進行排序,並得到數組的最後一個元素。

sorted_hash = posts.sort_by {|key,value| value} 
top_posters_group = sorted_hash[-1] 

之後,top_posters_group[0]將組的ID和top_posters_group[1]是職位數。

但無論如何這不是理想的解決方案。

在rails 3.1中用ruby 1.9.2測試。

相關問題