简体   繁体   English

Rails habtm:选择至少有一个关联的所有内容

[英]Rails habtm: select all that has at least one associated

I have 2 models: 我有2个型号:

class Section < ActiveRecord::Base
  has_and_belongs_to_many :posts
end

and

class Post < ActiveRecord::Base
  has_and_belongs_to_many :sections
end

I need to select all sections that has at least one associated post and order this sections by count of assotiated posts. 我需要选择至少有一个相关帖子的所有部分,并按照相关帖子的数量来订购此部分。 Can anyone help me? 谁能帮我?

I had no opportunity to test this code, but it looks about right. 我没有机会测试这段代码,但它看起来是正确的。

Section.select("sections.*, count(posts.id) AS post_count").
  joins(:posts).
  group("sections.id").
  order("post_count DESC")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM