Vin*_*ent 4 ruby database activerecord ruby-on-rails
假设我有两个模型Post和Category:
class Post < ActiveRecord::Base
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :posts
end
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以让我做类似的事情
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]
Run Code Online (Sandbox Code Playgroud)
换句话说,通过选定的类别ID将所有帖子的集合"拆分"为数组
Har*_*tty 13
尝试上课时的group_by
功能Array
:
posts.group_by(&:category_id)
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅API 文档.
警告:
当潜在数据集很大时,不应在Ruby代码中执行分组.group_by
当最大可能的数据集大小<1000时,我使用该函数.在您的情况下,您可能有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
Run Code Online (Sandbox Code Playgroud)