Ruby on rails 活动记录:按ceratin条件查找记录
我的目标是找到三位审查次数超过1次且平均评分>=4的医生 目前我正在使用这项服务Ruby on rails 活动记录:按ceratin条件查找记录,ruby-on-rails,ruby,activerecord,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)
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
这很慢
我的医生模型:
class Doctor < ApplicationRecord
has_many :reviews, dependent: :destroy
def average_rating
reviews.count == 0 ? 0 : reviews.average(:rating).round(2)
end
end
但是,如果“平均评分”是一种实例方法,我如何才能找到平均评分>=4的医生并按最高评分排序呢?多亏了这个答案
我的最终解决办法是
Doctor.joins(:reviews).group('doctors.id').order('AVG(reviews.rating) DESC').limit(3)
为了找到“有1个或多个”评论,您只需
Doctor.joins(:评论)
。为了找到“超过1”的医生(这就是你写的),你实际上需要做Doctor.joins(:reviews.group('doctors.id')。拥有('count(doctors.id)>1')
但是如果“平均评分”为0,我如何找到平均评分>=4的医生并按最高评分排序是一种实例方法吗?
您只需尝试Doctor.includes(:reviews).where(“reviews.avarage(:rating).round(2)>=?”,4).group('doctors.id')。having('count(doctors.id)>0')
或在上面创建一个作用域并使用该作用域
doctors_with_reviews = Doctor.joins(:reviews).group('doctors.id').having('count(doctors.id) > 0')
Doctor.joins(:reviews).group('doctors.id').order('AVG(reviews.rating) DESC').limit(3)