Rails 4范围模型:只有拥有孩子的父母

时间:2014-04-16 21:13:08

标签: activerecord ruby-on-rails-4 scope associations

我在Rails 4中有2个模型

 course.rb
 has_many :reviews

 review.rb
 belongs_to :course

仅对已经过审核的课程进行范围的最佳方法是什么?这有两种方式:

 1. scope :with_reviews, -> { joins(:reviews).where(:reviews => { :id => !nil }) }

counter_cache:在review.rb和

中为true
 2. scope :with_reviews, -> { where('reviews_count > ?', 0) }

还有另一种更好的方法吗?

THX

2 个答案:

答案 0 :(得分:2)

试试这个

Course.joins(:reviews).group('reviews.course_id').having('count(reviews.id) > 0')

答案 1 :(得分:0)

scope :with_reviews, -> { joins(:reviews).select("DISTINCT courses.*")}