1

私は現在、次のものを持っています:

users = User.all   
comments = users.collect(&:comments)

ただし、コメントが数千ある場合は、各ユーザーから 10 件のみを収集して、実行されるデータベース クエリの数を制限したいと考えています。これを行う方法はありますか?

4

4 に答える 4

1
users = User.all
comments = users.collect { |user| user.comments.limit(10) }

または、モデル内の別の関連付けを使用して:

has_many :first_comments, :class_name => "Comment", :limit => 10

これにより、2 つのデータベース クエリのみが生成されます。

users = User.includes(:first_comments)
comments = users.collect(&:first_comments)
于 2012-08-12T08:09:12.723 に答える
0

これを試して

comments = Comment.where(:user_id=>users).limit(10)

また

comments = Comment.all(:conditions => {:user_id=>users}, :limit => 10)

自分に合ったものならどれでも使えます

于 2012-08-12T07:14:10.207 に答える
0

クエリの点で最も簡単なのは、少し複雑に見えます。

Comment.where(["user_id IN (?)", users.collect(&id) ]).limit(10)

あなたの並べ替え順序は、デフォルトのスコープによってどこかに設定されていると思います。

レール 2:

Comment.all(:conditions => ["user_id IN (?)", users.collect(&id) ], :limit => 10)
于 2012-08-12T07:24:35.943 に答える
0
users = User.all
comments = Comment.order("DESC created_at").limit(10).all

または、これらの最近の 10 件のコメントのユーザーのみが必要な場合は、試すことができます

comments = Comment.includes(:users).order("DESC created_at").limit(10).all
users = comments.map(&:user)
于 2012-08-12T07:27:00.200 に答える