使用named_scope根据计数值进行选择

时间:2011-06-10 20:27:35

标签: ruby-on-rails activerecord

例如,假设我有类似BlogCategory的东西,它有一个带有BlogPost的HABTM,我想只选择实际在BlogPost中使用过的BlogCategories

named_scope :published, {
  :include    => :blog_posts,
  :select     => 'blog_categories.*, count(blog_posts.id) as post_count',
  :group      => 'blog_categories.id having post_count > 0',
  :conditions => 'blog_posts.published = 1',
}

我遇到的问题是:选择此部分似乎被rails完全忽略,因此count字段不会被放入查询中,我最终得到错误“Unknown column'post_count 'in'有条款'“

1 个答案:

答案 0 :(得分:1)

我不知道为什么它不识别post_count但它应该适用于:

  :group      => 'blog_categories.id having count(blog_posts.id) > 0',