列更改时的ActiveRecord回调

时间:2013-02-07 14:20:05

标签: ruby-on-rails-3 activerecord

我有以下关系模型:

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上运行。 我缺少什么?

修改:这是应用流程

  1. 用户(患者类)保存约会的约会:零和一些doctor_id。
  2. 如果pending.date已过,则可以通过“
  3. 在表单上编辑或设置appointment.rating
  4. 然后我需要更新appointment.doctor.average_rating

1 个答案:

答案 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