0

私は2つのモデルを持っています:

class Section < ActiveRecord::Base
  has_and_belongs_to_many :posts
end

class Post < ActiveRecord::Base
  has_and_belongs_to_many :sections
end

関連付けられた投稿が少なくとも 1 つあるすべてのセクションを選択し、関連付けられた投稿の数でこのセクションを並べ替える必要があります。誰でも私を助けることができますか?

4

1 に答える 1

2

このコードをテストする機会はありませんでしたが、ほぼ正しいように見えます。

Section.select("sections.*, count(posts.id) AS post_count").
  joins(:posts).
  group("sections.id").
  order("post_count DESC")
于 2013-06-23T11:16:37.693 に答える