Rails 4& ActiveRecord:如果所有者存在,则防止依赖性破坏

时间:2014-05-08 05:38:19

标签: ruby-on-rails activerecord ruby-on-rails-4

鉴于以下类别:

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

class Profile < ActiveRecord::Base
    belongs_to :user
end

如何阻止ActiveRecord销毁所有者用户所在的配置文件?我的意思是,如果有用户拥有该配置文件,则不应该销毁该配置文件。

我这样做了:

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

在我看来,这是一个过度工作的解决方案。 Rails或ActiveRecord是否提供更好,更简洁的解决方案?

0 个答案:

没有答案