سؤال

I have a 2 models in Rails 4

 course.rb
 has_many :reviews

 review.rb
 belongs_to :course

What is the best way to scope only the courses which have been reviewed? Here are two ways:

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

counter_cache: true in review.rb and

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

Is there another better way to do so?

Thx

هل كانت مفيدة؟

المحلول

try this

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

نصائح أخرى

scope :with_reviews, -> { joins(:reviews).select("DISTINCT courses.*")}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top