Given the following classes:
class User < ActiveRecord::Base has_one :profile, dependent: :destroy end class Profile < ActiveRecord::Base belongs_to :user end
How to prevent ActiveRecord from destroying the profile that the owner has? I mean, it should not be possible to destroy the profile if there is a user who owns it.
I did like this:
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 that this worked. Do Rails or ActiveRecord provide a better and more concise solution?
ruby-on-rails activerecord ruby-on-rails-4
hector
source share