2010-07-16 25 views
4

比方說,我有兩個型號帖子和類別:「分裂」的ActiveRecord收集

class Post < ActiveRecord::Base 
    belongs_to :category 
end 

class Category < ActiveRecord::Base 
    has_many :posts 
end 

有沒有,讓我做這樣的事情

posts = Post.find(:all) 

p = Array.new 

p[1] = posts.with_category_id(1) 
p[2] = posts.with_category_id(2) 
p[3] = posts.with_category_id(3) 
... 

or 

p = posts.split_by_category_ids(1,2,3) 

=> [posts_with_category_id_1, 
    posts_with_category_id_2, 
    posts_with_category_id_3] 

換句話說,「分裂的方法'通過選定的類別ID將所有帖子收集到數組中

回答

11

嘗試在Arraygroup_by功能:

posts.group_by(&:category_id) 

參考API documentation更多細節。

警告:

分組不應該在Ruby代碼執行時的潛在數據集可大了。當最大可能數據集大小爲< 1000時,我使用group_by函數。在您的情況下,您可能有1000個Post s。處理這樣的數組會對您的資源造成壓力。依靠數據庫來進行分組/排序/匯聚等

這裏是一個辦法做到這一點(類似的解決方案是通過nas建議)

# returns the categories with at least one post 
# the posts associated with the category are pre-fetched 
Category.all(:include => :posts, 
    :conditions => "posts.id IS NOT NULL").each do |cat| 
    cat.posts 
end 
+0

'group_by'解決方案正是我所期待的,謝謝! – Vincent 2010-07-16 17:33:15

+0

很好的答案謝謝 – ALFmachine 2017-01-21 03:24:12

0

當然,但考慮到您的模型關係,我認爲您需要以相反的方式來看待它。

p = [] 
1.upto(some_limit) do |n| 
    posts = Category.posts.find_by_id(n) 
    p.push posts if posts 
end 
+0

是的,但是這樣一來就會運行some_limit SQL查詢和我想只使用一個查詢(帖= Post.find(:所有))如果可能的話。 – Vincent 2010-07-16 01:15:14

0

像這樣的東西可能會奏效(郵政的實例方法,未經測試):

def split_by_categories(*ids) 
    self.inject([]) do |arr, p| 
    arr[p.category_id] ||= [] 
    arr[p.category_id] << p if ids.include?(p.category_id) 
    arr 
    end.compact 
end 
0

而是讓所有的職位,然後做一些操作他們對其進行分類這是一個有點性能密集型練習,我寧願用預先加載像這樣

categories = Category.all(:include => :posts) 

,這將產生一個SQL查詢來獲取您所有的帖子和類別的對象。然後你就可以輕鬆地在它們之間迭代:

p = Array.new 
categories.each do |category| 
    p[1] = category.posts 
    # do anything with p[1] array of posts for the category 
end 
+0

@nas這將返回甚至沒有帖子的類別。您必須添加附加條件才能過濾沒有帖子的類別。 – 2010-07-16 17:04:21

+0

@KandadaBoggu我不認爲你是否得到沒有發佈帖子的類別很重要,因爲根據問題@Vincent正在對不屬於類別的帖子進行操作。而當你調用'category.posts'時,你將得到一個空數組,並且遍歷一個空數組不會執行你的代碼塊,因此沒有任何效果。所以恕我直言,沒有條件在這裏根據情況需要。 – nas 2010-07-16 20:49:10

+0

由於帖子有類別,@文森特的邏輯不需要處理沒有帖子的類別的場景。最好通過添加附加條件來過濾數據庫級別的空白類別。 – 2010-07-16 21:52:03