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