我们有一个非常简单的小组和角色模型
class Group < ActiveRecord::Base
has_many :roles, :dependent => :destroy
end
class Role < ActiveRecord::Base
belongs_to :group
after_destroy :ensure_last_role
private
def ensure_last_role
raise "Can't delete last role" if group.roles.count.zero?
end
end
after_destroy完美运行,不允许最后一个角色被意外破坏。但这也可以防止在以下情况下销毁该组:dependent =&gt; :destroy试图摧毁所有角色。当一个组被破坏或是否有更好的方法来解决这个问题时,是否有可能不调用ensure_last_role?
答案 0 :(得分:2)
在玩了一会儿之后,我找到了一个解决方案,它没有使用dependent: :destroy
中内置的Rails作为关系,因为我无法以正确的顺序触发回调。缓存也存在一些问题,因此每次尝试销毁Role
时,都会进行一次小型SQL查询,以查看其组是否仍存在于数据库中:
> role.destroy
Group Exists (0.2ms) SELECT 1 FROM "groups" WHERE "groups"."id" = 18 LIMIT 1
无论如何,这是完整的型号代码:
class Group < ActiveRecord::Base
has_many :roles
after_destroy :destroy_roles
def destroy_roles
roles.each { |r| r.destroy }
end
end
class Role < ActiveRecord::Base
belongs_to :group
before_destroy :ensure_last_role, if: "Group.exists?(group_id)"
private
def ensure_last_role
raise "Can't delete last role" if group.roles.count == 1
end
end