ruby-on-rails – ‘拆分’ActiveRecord系列
发布时间:2020-12-17 04:03:25 所属栏目:百科 来源:网络整理
导读:假设我有两个模型Post和Category: class Post ActiveRecord::Base belongs_to :categoryendclass Category ActiveRecord::Base has_many :postsend 有没有一种方法可以让我做类似的事情 posts = Post.find(:all)p = Array.newp[1] = posts.with_category_id
假设我有两个模型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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |