销毁前验证 [英] Validate Before Destroy

查看:43
本文介绍了销毁前验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个类:SchoolAccountAdministratorship.

I have three classes: School, Account, and Administratorship.

学校

has_many :administatorships
has_many :administrators, :through => :administratorships

帐户

has_many :administratorships

管理

belongs_to :account
belongs_to :school

before_destroy :confirm_presence_of_alternate_administratorship_in_school

protected

def confirm_presence_of_alternate_administratorship_in_school
    unless school.administrators.count(["administratorships.account_id != #{id}"]) > 0
        errors.add_to_base "The school must have at least one administrator"
    end
end

现在,我想要发生的是当我在 Administratorship 的实例上调用 destroy 时,它会向模型添加错误并防止破坏该模型.我已经删除了 unless 语句,看看这是否会阻止添加错误,但事实并非如此.模型上的错误似乎并不能阻止破坏的发生.

Now, what I would like to happen is when I call destroy on an instance of Administratorship, for it to add an error to the model and prevent the destruction of the model. I have removed the unless statement to see if that was preventing the error from being added, but it wasn't the case. It seems that having errors on the model does not prevent the destroy from occurring.

所以我的问题是,有什么办法可以防止使用验证发生破坏?我意识到我可以定义一个只有在满足上述条件时才销毁的方法,但验证方法似乎是一个更优雅的解决方案.

So my question is, is there any way I can prevent the destroy from occurring using validations? I realize I could define a method that destroys only if the above condition is met, but it seems that a validation approach is a more elegant solution.

推荐答案

如果你从 before_destroy 方法返回 false,它会阻止销毁.

If you return false from that before_destroy method, it will prevent the destruction.

这篇关于销毁前验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆