We have small class, that has a related class
class Car
has_one :engine, :dependent => :destroy
after_update :save_engine
delegate :oil_level, :oil_level=, :to => :engine
def save_engine
engine.save if engine
end
end
As you can tell, we are trying to work-around the problem that childs are not automatically saved in rails. So we can set the oil_level on car, and it will store it in engine correctly when saving.
Now what happens when we try to delete the car? Apparently the engine is never deleted, and this is caused by the after_update which will re-save the just deleted engine. So the car is succesfully deleted, but the engine is recreated (a new id), and no longer linked to a car. I want the engine to be deleted correctly.
I did find a solid work-around:
class Car
has_one :engine, :dependent => :destroy
after_update :save_engine
before_destroy :set_destroying
delegate :oil_level, :oil_level=, :to => :engine
def set_destroying
@destroying = true
end
def save_engine
engine.save if engine && !@destroying
end
end
But it still feels a bit dirty, like there should be a better way to do this.
It seems a bit unlogical that after_update is called when destroying.
Is there a specific rails-way to know what action is actually in progress in a callback (saving/creating/destroying) ?.
In short: what is the proper way to handle this? Or is this actually some kind of rails-bug? Or is this intended behaviour?
Haven’t done Rails for a while, so I may be off topic, but have you considered using the
:autosaveoption?