Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails has_many associations delete parent object but not children

The scenario is that there is two models one is Room and other one is Tickets and the relationship is Room has_many :tickets.

The requirement is that when a room is deleting tickets should not be delete. How to accomplish this because tickets table have foreign key called as room_id ?

And Suppose if I am able to do this then how I will be able to get the room information for that particular ticket ?

like image 484
Anand Shrivastava Avatar asked Dec 04 '25 18:12

Anand Shrivastava


2 Answers

This is a general behaviour of Rails. I guess you're using the dependent: :destroy in your association.

What you would want to do is dependent: :nullify. This would delete your room object without deleting the associated tickets and only update the room_id to null in the tickets

class Room < ActiveRecord::Base
    has_many :tickets, dependent: :nullify
end

As per your second question to access the room details after deletion, i would suggest you to use soft_delete instead of actual deleting. Here, what you'll be doing is that when the room is being deleted, instead of actully deleting it, you'll soft delete it. Hence, the tickets records will persists and you'll also be able to use the room details.

There are gems available for same. One such gem is Paranoia. You can look up various tutorials on this gem.

Hope this is helpful. Let me know if you need any other guidance.

like image 73
Aakanksha Avatar answered Dec 06 '25 07:12

Aakanksha


you can do this

class Room < ActiveRecord::Base
 has_many :tickets,dependent: :nullify
end

checkout this

like image 26
Anand Avatar answered Dec 06 '25 07:12

Anand