G Sree Teja Simha
G Sree Teja Simha

Reputation: 505

Rails: delete belongs_to object when old object is replaced with new

Here is the scenario

I have a Hospital model and a Contact model. For some situation, we have this type of relation.

Note: This is not the actual code.I had to simplify it to get rid of unnecessary lines of code.

class Hospital < ActiveRecord::Base  
     attr_accessible :contact_id  
     belongs_to :contacts
end

class Contact <ActiveRecord::Base
    attr_accessible :phone_number
end

When ever I want to change the contact number, we create a new contact and replace the contact_id from Hospital with this new contact object's id.

When ever this happens, old contact needs to be destroyed. Is there a relation condition similar to :dependent=>:destroy which can do the same automatically? If not is there a technique which I should follow to achieve this behavior.

Thank you.

Upvotes: 3

Views: 1143

Answers (2)

Matt
Matt

Reputation: 14038

There is no inbuilt functionality to do what you want, but you can keep the functionality in the model where it belongs via callbacks.

Write a method called by an appropriate callback (:after_update for example) that checks whether contact_id has changed, gets the old value and destroys that object:

class Hospital < ActiveRecord::Base  
  attr_accessible :contact_id  
  belongs_to :contacts

  after_update :check_contact

  def check_contact
    if contact_id_changed?
      Contact.find(contact_id_was).destroy
    end
  end
end

I haven't tested this but it should get you started, here is the documentation for the relevant tools:

Upvotes: 2

Hemanth Raju
Hemanth Raju

Reputation: 1

There is no specific functionality as of my knowledge. Have some queries, Why are you creating new object of Contact? instead can update the same object. An alternative would be just storing the ID before you have a update on Hospital object and destroy the Contact object after successful update but this would not be a good practice. Thank you.

Upvotes: -1

Related Questions