gpt4 book ai didi

rspec - Rails 5 before_destroy 抛出(:abort)

转载 作者:行者123 更新时间:2023-12-03 23:15:47 29 4
gpt4 key购买 nike

我正在使用旧版 Rails 应用程序,该应用程序已随 Rails 的每个主要版本进行了认真升级,我们目前使用的是 Rails 5.1,但我无法获得 before_destroy如果验证失败,则防止删除

我一直在读return false已被弃用,我们都应该使用 throw :abort但两者都不起作用。我没有收到任何错误,尽管存在 throw,但连接记录却被删除了

用户.rb:

class User < ApplicationRecord
has_many :permission_users
has_many :permissions, through: :permission_users, dependent: :destroy
end

加入模型permission_user.rb:
class PermissionUser < ApplicationRecord
belongs_to :user
belongs_to :permission

before_destroy :check_before_removing!

private

def check_before_removing!
if not_valid? # condition isn't important
errors.add :base, exception.message
throw(:abort)
end
end
end

我的规范:
specify "cannot have their admin permissions revoked" do
expect {
admin.permissions.delete admin_permission
}.to change { admin.permissions.count }.by(0)
end

# => expected `admin.permissions.count` to have changed by 0, but was changed by -1

最佳答案

a catch with this callback :

before_destroy callbacks should be placed before dependent: :destroy associations (or use the prepend: true option), to ensure they execute before the records are deleted by dependent: :destroy.



所以请尝试
before_destroy :check_before_removing!, prepend: true

关于rspec - Rails 5 before_destroy 抛出(:abort),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51073865/

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