2

モデル ユーザーがいて、多くの投稿があります。最初の 5 人のユーザーをクエリするには、次のようにします。

User.all :limit => 5

これは良いユーザーを返しますが、各ユーザーが持っている投稿の数を取得するときに、DB に再度クエリを実行します。

a_user.posts.count

このクエリを回避して、最初のクエリでカウントを取得する方法はありますか? ユーザーをループしていますが、ユーザーの投稿数を照会するたびにブロックされます。

4

2 に答える 2

4

Railsには組み込みのメソッドがあり、has_manyのような関連付けを宣言するときは、trueに設定する必要があります。また、データベースに列を追加する必要があります。

アソシエーションcounter_cache: trueを宣言するときに設定しますhas_many

データベースに追加#{table_name}_countすると、自動的にインクリメントおよびデクリメントされるため、最初の5人のユーザーを照会するときにこの列を直接選択できます。

詳細:

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

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

于 2013-01-07T15:26:29.597 に答える
3

The method your looking for the the rails eager loading #includes, which will still create two queries (but not the 6 if you do User.all, :limit=>5 and then user.posts on each), but will load the posts in one query:

User.includes(:posts).limit(5)

which should create the SQL:

SELECT * FROM users LIMIT 5
SELECT posts.* FROM posts
  WHERE (posts.user_id IN (1,2,3,4,5)) # Numbers are found ID

You can find this information from Active Record Query Guide

于 2013-01-07T15:12:15.540 に答える