ruby-on-rails - “拆分”ActiveRecord 集合

标签 ruby-on-rails ruby database activerecord

假设我有两个模型 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/

相关文章:

ruby - 安装 el capitan 后 compass 不工作

mysql - 过滤掉分组行的 MAX() 日期之前一年以上的任何内容

mysql - 如何将mysql日期列的现有内容批量移动到不同类型的新内容?

ruby-on-rails - 在 Windows 上使用 Ruby 进行开发

ruby-on-rails - Ruby on Rails 堆栈级别太深

ruby-on-rails - Ruby on Rails - 连接两个表将结果添加到 JSON

php - 在 cakephp 3 中动态更改数据库连接

ruby-on-rails - 上帝没有运行 : The server is not available (or you do not have permissions to access it)

ruby-on-rails - 将枚举值映射到字符串类型而不是整数的可能性

c++ - 从 C++ 登录并使用 Rails