我有一个教师模型,它接受klasses的_nested_attributes_for。如果klass中有用户并且我想打印验证消息,我不希望能够删除klass。
这就是我所拥有的。。。
class Teacher < ActiveRecord::Base
accepts_nested_attributes_for :klasses, :reject_if => proc { |a| a['name'].blank? }, :allow_destroy => true
end
class Klass < ActiveRecord::Base
belongs_to :teacher
has_many :users
before_destroy :reject_if_has_users
private
def reject_if_has_users
if users.length > 0
errors.add_to_base "You cannot delete this class as it contains users."
false
else
true
end
end
end
当我使用accepts_nested_attributes_for并传递"klasses_attributes"=>{"0"=>{"name"=>"test"、"_destroy"=>"1"、"id"=>"17183"}哈希时,我希望在尝试从包含用户的教师中删除klass时验证失败。
如果我没有error.add_to_base行,上面的方法将防止klass被删除。但是,它不会导致显示验证消息。当我有那一行时,它不会阻止删除。
谢谢,
Tim
删除记录时不会进行验证,只有在保存记录时才会进行验证。在我的一个项目中,我处理这个问题的方法是在模型中引发一个异常,然后在控制器中从该异常中恢复并显示一个闪烁警报。像这样:
型号:
class Klass < ActiveRecord::Base
before_destroy :reject_if_has_users
private
def reject_if_has_users
raise "You cannot delete this class as it contains users." if users.length > 0
end
end
教师控制器:
def update
# Code for updating the teacher
rescue RuntimeError => e
redirect_to teacher_url(@teacher, :alert => e.message) and return false
end