ruby – 当销毁失败时,我可以在活动管理员中有一条flash消息吗?
发布时间:2020-12-17 04:26:33 所属栏目:百科 来源:网络整理
导读:在我的应用程序中,一些资源无法销毁.所以我写了这样的模型: before_destroy :destroy_checkdef destroy_check if some_reason? errors.add(:base,'cannot destroy this resource!') end errors.blank?end 然后,当我在ActiveAdmin中单击destroy按钮时,没有任
在我的应用程序中,一些资源无法销毁.所以我写了这样的模型:
before_destroy :destroy_check def destroy_check if some_reason? errors.add(:base,'cannot destroy this resource!') end errors.blank? end 然后,当我在ActiveAdmin中单击destroy按钮时,没有任何显示:没有错误,没有消息,并且记录没有被真正销毁.如何在销毁失败时显示错误消息? 解决方法
首先使用你的模型的before_destroy回调来检查记录是否可以被销毁(如果学生已经登录,这里):
class Student < ActiveRecord::Base before_destroy :before_destroy_check_for_groups def before_destroy_check_for_groups if StudentInGroup.exists?(student_id: self.id) errors.add(:base,I18n.t('app.student_signed_in')) return false end end end 这是常见且简单的,您可以为您想要的每个型号执行此操作. 这是一个技巧. class ActiveAdmin::ResourceController def check_model_errors(object) return unless object.errors.any? flash[:error] ||= [] flash[:error].concat(object.errors.full_messages) end end class ActiveAdmin::ResourceDSL alias_method :old_run_registration_block,:run_registration_block def run_registration_block(&block) old_run_registration_block(&block) instance_exec { after_destroy :check_model_errors } end end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |