具有 has_many 关联的 Active Record 回调

Active Record callbacks with has_many association

我想在每次将子对象添加到父对象(has_many 关联)时 运行 一个 before_saveafter_add 回调。在回调中,我想根据所有子级(课程)的 end_date 属性在父级(队列)上设置 end_date 属性。

class Cohort < ActiveRecord::Base
  has_many :courses   
  before_save :update_end_date

  def update_end_date
    self.end_date = courses.order(:end_date).last.try(:end_date)
  end
end

我遇到的问题是课程尚未在 before_save 回调中保存到数据库,因此 courses.order(:end_date) 不会 return 新添加的课程).

我可以使用几种解决方法(例如使用 Ruby courses.sort_by 方法或使用 after_saveupdate),但我的印象是使用 Active如果可能,记录 order 方法在效率和最佳实践方面将是可取的。 before_save 中的 Active Record 有没有办法做到这一点,或者什么是最佳实践?这似乎会经常出现,但我很难找到适合我的解决方案,所以我觉得我一定是想错了。谢谢!

如果课程结束日期晚于同类群组结束日期,您可以对可能更新同类群组的课程进行事后保存。以及课程后的销毁,告诉队列更新其结束日期以对应于剩余课程。

class Course < ActiveRecord::Base
  belongs_to :cohort
  after_save :maybe_update_cohort_end_date
  after_destroy :update_cohort_end_date

  def maybe_update_cohort_end_date
    if cohort && self.end_date > cohort.end_date
      cohort.end_date = self.end_date
      cohort.save
    end
  end

  def update_cohort_end_date
    cohort.update_end_date if cohort
  end
end

class Cohort < ActiveRecord::Base
  has_many :courses

  def update_end_date
    self.end_date = courses.order(:end_date).last.try(:end_date)
  end
end

这样,您仅在新课程或更新课程的结束日期会更改同类群组结束日期时才进行更新。但如果课程被删除也会捕获然后检查结束日期应该是什么