Without getting into real detail, I need this behavior because of a legacy database (Actually, it is not all that "legacy". It is more "enterprise-esque".).
Anyway . . .
Question: Can an ActiveRecord object invoke an instance method, then, while executing that method, destroy itself?
Code example:
@some_object.some_methodClass SomeObject < ActiveRecord::Base
def some_method
...Some really awesome stuff happens here...
self.destroy
end
end
At first, I thought it would work. There are plenty of times where I have invoked a destroy method on an AR object, then use that same AR object later. I do this in controller action methods often.
But, even as I was writing that logic, it did not feel correct. But, Ruby has a tendency to surprise me. So, I gave it a shot.
It turns out that you cannot do this. I am not sure if this is a Ruby or ActiveRecord behavior. If anyone knows, please comment.
To me, it seems like appropriate behavior.
You should not be able to start some set of tasks, one of which causes you to kill yourself, but requires you to finish off the rest of the tasks.
I accomplished the same behavior by creating another object within the instance method, and destroying that object.
Code Example:
@some_object.some_methodClass SomeObject < ActiveRecord::Base
def some_method
...Some really awesome stuff happens here...
SomeObject.find(self).destroy
end
end
Has anyone else come up against this? Am I solving this problem correctly?
5 comments: