2013-06-27 47 views

回答

1

您既可以使用示波器这样

scope :with_posts, -> { includes(:posts).where("posts.id IS NOT NULL") } 

或使用counter_cache

class Category < ActiveRecord::Base 
    has_many :posts 
    scope :with_posts, -> { where("posts_count > ?", 0) } 
end 

class Post < ActiveRecord::Base 
    belongs_to :category, counter_cache: true 
end 

注意,您必须到posts_count整型字段添加到categories表这个工作。建议您首次保存所有类别以填充此字段。

+0

某些原因您的解决方案不起作用 – Benjamin

+0

噢,我很抱歉:请检查更新后的答案! –

+0

当我在控制器上使用它的作品def show @categories = Category.where('posts_count>?',0) end – Benjamin