Rails 4 & ActiveRecord: prevent dependent destroy

2019-09-09 12:42发布

问题:

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?