Rails eager loading of counts?

后端 未结 5 1014
暖寄归人
暖寄归人 2021-02-02 14:50

Eager loading is nice with the include attribute

Post.find(:all, :include => :author)

I\'m wondering if you can also eager load counts, like

5条回答
  •  鱼传尺愫
    2021-02-02 15:10

    I just ran into this challenge and solved it this way:

    def trainee_counts
       @trainee_counts ||= Hash[Trainee.group(:klass_id).count]
    end
    
       # where the count is needed
       trainee_counts[klass_id].to_i
    

    One call to database and does not load trainees.

提交回复
热议问题