Rails相关模型聚合的性能改进

时间:2012-12-18 05:17:25

标签: mysql ruby-on-rails performance

我有一个名为Person and Person的模型有多个帖子。当我想查询每个人的帖子数时,需要花费很长时间来处理,因为它需要遍历每个人并查询每个帖子以获得聚合。

class Person < ActiveRecord::Base
has_many :posts
end

输出(JSON):

Person1
  PostsType1Count: 15
  PostsType2Count: 45
Person2
  PostsType3Count: 33
.
.
.

我想以最佳方式计算每个人的所有帖子数。什么是最好的解决方案?

2 个答案:

答案 0 :(得分:1)

如果你有一套小的预定义类型

,这是一种方法
class Person < ActiveRecord::Base
  has_many :type_1_posts, :class_name => 'Post', :conditions => 'post_type = 1'
  has_many :type_2_posts, :class_name => 'Post', :conditions => 'post_type = 2'
  has_many :type_3_posts, :class_name => 'Post', :conditions => 'post_type = 3'
end

然后你可以编写看起来像这样的代码来获取所有数据:

@all_people = Person.includes(:type_1_posts, :type_2_posts, :type_3_posts).all

帖子的热切加载允许每种类型的帖子的计数,以及每种类型的所有帖子。

如果您需要此代码的额外性能,因为您经常执行此查询,那么您可以考虑使用Rails 计数器缓存机制来跟踪Person上每种类型的计数对象

Rails的优点在于,在使代码更快阅读的过程中,您的主显示代码无需更改(添加计数器缓存会使添加/删除帖子变慢,因此您可能根本不需要它例)。

  1. 编写初始代码
  2. 使用急切加载使其更快
  3. 使用计数器缓存使其更快

答案 1 :(得分:0)

试试这个五月它会对你有用

    #In Controller
    @persons = Person.all
    #In View
    @persons.each do |person|
         person.posts.count # It will gives all posts count
         person.posts.collect{|x| true if x.type==1 }.compact.count #If you want to get the post counts based on type
    end

假设您想要获取任何方法只需检入控制台或调试是person.methods.sort它将提供所有方法。
尝试在rails控制台person.posts.methods也会给类型,然后根据类型检查计数。因为我不知道帖子模型中的哪些字段。检查一下。