Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
1 つの投稿には多くのコメントがあります。comments.count が 5 より大きいすべての投稿を選択したいと思います。
このようなもの: Post.all.joins(:comments).having("count >= 5")
comments_count投稿テーブルに列を追加し、これを追加する場合:
comments_count
class Comment < ActiveRecord::Base belongs_to :post, :counter_cache => true .. end
次に、投稿を保存すると、カウンターが更新されます。その時点で、クエリは非常に単純です。
Post.where("comments_count >= ?", 5).all
または、純粋な SQL コードにドロップすることもできます。しかし、男、ただカウンターに行く
関連:ネストされたモデルの数に基づいてソートするRailsクエリ?