假设我有两个模型 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 代码中执行分组。当最大可能的数据集大小小于 1000 时,我使用 group_by
函数。在您的情况下,您可能有 1000 个 Post
。处理这样的数组会给您的资源带来压力。依赖数据库进行分组/排序/聚合等。
这是一种方法(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
关于ruby-on-rails - “拆分”ActiveRecord 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3261154/