我的应用程序中有一个重要的模型,有许多关联。如果我想检查before_destroy回调中的所有引用,我必须执行以下操作:
has_many :models_1
has_many :models_2
mas_many :models_3
....
....
has_many :models_n
before_destroy :ensure_not_referenced
def :ensure_not_referenced
if models_1.empty? and models_2.empty? and models_3.empty? and ... and models_n.empty?
return true
else
return false
errors.add(:base,'Error message')
end
end
问题是,有没有办法立即执行所有验证? 感谢名单!
答案 0 :(得分:23)
您可以将:dependent => :restrict
选项传递给has_many
来电:
has_many :models, :dependent => :restrict
这样,只有在没有其他相关对象引用它时,您才能销毁该对象。
其他选项包括:
:destroy
- 销毁调用其destroy
方法的所有关联对象。:delete_all
- 删除所有关联的对象,不用调用他们的destroy
方法。:nullify
- 将相关对象的外键设置为NULL
,无需调用其保存回调。答案 1 :(得分:1)
将模块创建到app / models / concerns / verification_associations.rb中:
module VerificationAssociations
extend ActiveSupport::Concern
included do
before_destroy :check_associations
end
def check_associations
errors.clear
self.class.reflect_on_all_associations(:has_many).each do |association|
if send(association.name).any?
errors.add :base, :delete_association,
model: self.class.model_name.human.capitalize,
association_name: self.class.human_attribute_name(association.name).downcase
end
end
return false if errors.any?
end
end
在app / config / locales / rails.yml
中创建一个新的翻译密钥en:
errors:
messages:
delete_association: Delete the %{model} is not allowed because there is an
association with %{association_name}
在您的模型中包含模块:
class Model < ActiveRecord::Base
include VerificationAssociations
end