gpt4 book ai didi

ruby-on-rails - Rails 4 关联验证销毁

转载 作者:数据小太阳 更新时间:2023-10-29 08:44:52 25 4
gpt4 key购买 nike

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

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 会使用 delete 方法?然后我试了这个:

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

不,再次。

rails 似乎只是直接从数据库中删除连接关联(约会)。

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

最佳答案

从 rails 上 documentation

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

关于ruby-on-rails - Rails 4 关联验证销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32468562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com