Reputation: 85
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 ?
Upvotes: 2
Views: 2170
Reputation: 976
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.
Upvotes: 9
Reputation: 3886
Add dependent: :nullify
to has_many association, this will change foreign_key by a null after delete parent:
has_many :tickets, dependent: :nullify
Look at rails documentation: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many
Upvotes: 1