我有以下关系模型:
class Doctor
has_many :appointmets
# has attribute 'average_rating' (float)
end
class Appointment
belongs_to :doctor
# has_attribute 'rating' integer
end
我想设置一个回调,以便在每次约会被评级时设置doctor.average_rating
,即每次{约1}}约会上的约会被触及。
我试过这个:
rating
但是不起作用,class Appointment
after_update :update_dentist_average_rating, if: :rating_changed?
# also tried with after_save
private
def update_dentist_average_rating
ratings = Appointment.where(dentist_id: dentist.id).map(&:rating)
doctor.average_rating = ratings.reduce(:+) / ratings.size if ratings.any?
doctor.save
end
end
总是返回appointment.dentist.average_rating
。我似乎无法测试回调是否在nil
上运行。 我缺少什么?
修改:这是应用流程
答案 0 :(得分:3)
通过此回调实现了它,但我不知道这是否是最佳方式:
after_save if: :rating_changed? do |apt|
ratings = Appointment.where(doctor_id: 10).map(&:rating)
doctor.average_rating = ratings.reduce(:+) / ratings.size if ratings.any?
doctor.save!
end