Rails 4 & ActiveRecord: prevents freezes if the owner exists

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?

0
ruby-on-rails activerecord ruby-on-rails-4
source share

No one has answered this question yet.

See similar questions:

6
rails prevent the removal of the child if the parent is not removed as well

or similar:

10
What is the best way to override Rails ActiveRecord behavior?
5
3 rails connecting more than three tables
4
method_missing override not working
2
Rails 3 ActiveRecord & Postgres: sort by association
2
How to prevent ActiveRecord :: Observer from registering the deletion of dependent records if the parent record is destroyed?
0
multiple joints in rails
0
Rails: how to prevent deletion of records?
0
Rails relationships don't work for me
0
Rails ActiveRecord not working with two tables
-2
Upgrade rails of rails 2.2 to rails 4.2

All Articles