假设我有两个模型Post和Category:
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将所有帖子的集合“拆分”为数组
在Array类上尝试group_by函数:posts.group_by(&:category_id)
有关更多详细信息,请参阅API documentation.
警告:
当潜在数据集很大时,不应在Ruby代码中执行分组.当最大可能数据集大小为<时,我使用group_by函数. 1000.在您的情况下,您可能有1000个帖子.处理这样的数组会给你的资源带来压力.依靠数据库来执行分组/排序/聚合等. 这是一种方法(类似的解决方案由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
精彩评论