Rails 4 关联验证销毁

Rails 4 association validate destroy

我有两个模型通过第三个模型具有多对多关联。 例如:

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, through: :appointments
end

并使用 simple_form 我设置了这个复选框(医生表格):

...
= f.association :patients, as: :check_boxes
...

当我选中一些复选框时,保存后 rails 将在数据库中创建约会。

当我取消选中复选框时,rails 会破坏一些未选中的约会。

因此更新将等同于

physician.patient_ids = []

我想在删除之前验证约会。例如,如果约会有一些警告,我想在保存医生表格时显示警报验证错误。

所以,我想,也许 rails 会在约会时调用 destroy 方法,并尝试过:

class Appointment < ActiveRecord::Base

before_destroy :check_destroy
private
def check_destroy
  raise 'you can not do it!'
end

不,rails 刚刚在保存 Physician 时从数据库中删除了预约。

也许rails会使用删除方法?然后我试了这个:

  class Appointment < ActiveRecord::Base
  def delete
    raise 'you can not do it!'
  end

不,又一次。

似乎 rails 直接从数据库中删除加入关联(约会)。

如何预防?我想在保存 Physician 之前验证所有将被删除的约会,并在无法删除某些约会时向 Physician 添加错误。

来自railsdocumentation

Similar to the normal callbacks that hook into the life cycle of an Active Record object, you can also define callbacks that get triggered when you add an object to or remove an object from an association collection.

来自文档的示例

class Project
  has_and_belongs_to_many :developers, after_add: :evaluate_velocity

  def evaluate_velocity(developer)
    ...
  end
end

所以在你的特定情况下尝试

  has_many :patients, through: :appointments, before_remove :check_remove