私は現在、次のものを持っています:
users = User.all
comments = users.collect(&:comments)
ただし、コメントが数千ある場合は、各ユーザーから 10 件のみを収集して、実行されるデータベース クエリの数を制限したいと考えています。これを行う方法はありますか?
私は現在、次のものを持っています:
users = User.all
comments = users.collect(&:comments)
ただし、コメントが数千ある場合は、各ユーザーから 10 件のみを収集して、実行されるデータベース クエリの数を制限したいと考えています。これを行う方法はありますか?
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)
これを試して
comments = Comment.where(:user_id=>users).limit(10)
また
comments = Comment.all(:conditions => {:user_id=>users}, :limit => 10)
自分に合ったものならどれでも使えます
クエリの点で最も簡単なのは、少し複雑に見えます。
Comment.where(["user_id IN (?)", users.collect(&id) ]).limit(10)
あなたの並べ替え順序は、デフォルトのスコープによってどこかに設定されていると思います。
レール 2:
Comment.all(:conditions => ["user_id IN (?)", users.collect(&id) ], :limit => 10)
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)