我有以下关系模型:
class Doctor
has_many :appointmets
# has attribute 'average_rating' (float)
end
class Appointment
belongs_to :doctor
# has_attribute 'rating' integer
end
我想设置一个回调,以在每次对约会进行评级时设置doctor.average_rating
,即每次触摸约会表上的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
。我似乎无法测试回调是否在appointment.save
上运行我缺少什么
编辑:这是应用程序流
- 一个用户(属于Patient类别)保存了一个具有评级:nil和一些doctor_id的预约
- 如果约会日期已过,则可以通过"在表单上编辑或设置约会日期
- 然后我需要更新任命.doctor.average_rading
通过这个回调实现了它,尽管我不知道这是否是最好的方法:
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