活动记录:通过ceratin条件查找记录

时间:2018-04-17 08:31:14

标签: ruby-on-rails ruby activerecord

我的目标是找到三位医生,评论次数超过1次且平均评分> = 4

目前我正在使用此服务

class RatingCounterService
  def get_three_best_doctors
    doctors = find_doctors_with_reviews
    sorted_doctors = sort_doctors(doctors)
    reversed_hash = reverse_hash_with_sorted_doctors(sorted_doctors)
    three_doctors = get_first_three_doctors(reversed_hash)
  end

  private

  def find_doctors_with_reviews
    doctors_with_reviews = {}

    Doctor.all.each do |doctor|
      if doctor.reviews.count > 0 && doctor.average_rating >= 4
        doctors_with_reviews[doctor] = doctor.average_rating
      end
    end

    doctors_with_reviews
  end

  def sort_doctors(doctors)
    doctors.sort_by { |doctor, rating| rating }
  end

  def reverse_hash_with_sorted_doctors(sorted_doctors)
    reversed = sorted_doctors.reverse_each.to_h
  end

  def get_first_three_doctors(reversed_hash)
    reversed_hash.first(3).to_h.keys
  end
end

这很慢。

My Doctor模特:

class Doctor < ApplicationRecord
  has_many :reviews, dependent: :destroy

  def average_rating
    reviews.count == 0 ? 0 : reviews.average(:rating).round(2)
  end
end

评论模型:

class Review < ApplicationRecord
  belongs_to :doctor

  validates :rating, presence: true
end

我可以通过此请求找到所有超过1条评论的医生

doctors_with_reviews = Doctor.joins(:reviews).group('doctors.id').having('count(doctors.id) > 0')

但是,如果“平均评分”是实例方法,我怎样才能找到平均评分≥4的医生并按最高评分排序?

1 个答案:

答案 0 :(得分:0)

感谢您的回答:highest_rated scope to order by average rating

我的最终解决方案是

Doctor.joins(:reviews).group('doctors.id').order('AVG(reviews.rating) DESC').limit(3)