ActiveRecord的查询,包括协会数 [英] Activerecord query to include count of associations

查看:150
本文介绍了ActiveRecord的查询,包括协会数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,用户,它有很多帖子。要查询前5个用户,我做的:

I have a model User and it has many posts. To query first 5 users, I do:

User.all :limit => 5

它返回一个用户,这是很好的,但越来越#帖子每个用户的计数时,它再次查询数据库:

which returns a user which is good, but when getting the count of # of posts each user has, it queries the DB again:

a_user.posts.count

有没有一种方法可以让我避免这种情况的查询,并获得数与第一个查询?我是通过用户和IT组,每组一次查询用户的帖子的计数循环。

Is there a way I can avoid this query and get the count with the first query ? I am looping through users and it blocks each time it query for user's post's count.

推荐答案

的Rails有一个内置的方法,有宣称就像has_many关联时,必须设置为true,而且,你必须将列添加到数据库中。

Rails has a built in method, that has to be set to true when declaring associations like has_many, and also, you must add a column to the database.

设置 counter_cache:真正的在声明的has_many 协会

添加#{table_name的} _count 到数据库中,它会增加或减少自动,这样你就可以直接在查询前五用户选择此列。

add #{table_name}_count to the database and it will be incremented and decremented automatically, so you can select this column directly when you query for the first five users.

这更多信息:

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

http://railscasts.com/episodes/23-counter-cache-column

这篇关于ActiveRecord的查询,包括协会数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆