Rails 4 & ActiveRecord: prevent dependent destroy if owner exists

我是研究僧i 提交于 2019-12-25 09:39:28

问题


Given the following classes:

class User < ActiveRecord::Base
    has_one :profile, dependent: :destroy
end

class Profile < ActiveRecord::Base
    belongs_to :user
end

How do I prevent ActiveRecord from destroying a profile which owner user exists? I mean, it should not be possible to destroy a profile if there's a user who owns it.

I did in this way:

class User  < ActiveRecord::Base
    has_one :profile
    after_destroy :destroy_profile

    private
        def destroy_profile
            profile.destroy
        end
end

class Profile  < ActiveRecord::Base
    belongs_to :user
    before_destroy :check_owner_user

    def check_owner_user   
        unless user.nil?     
            raise CustomException.new("Cannot delete while its owner user exists.")
        end 
    end
end

It seems to me an over worked solution. Does Rails or ActiveRecord provide a better and more concise solution?

来源:https://stackoverflow.com/questions/23533552/rails-4-activerecord-prevent-dependent-destroy-if-owner-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!