Can an ActiveRecord object destroy itself?

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_method

Class 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_method

Class 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?


About this entry


5 comments:

  1. Steel October 17, 2008 at 11:20 AM

    Does a post method execution handler work? I forget what the exact term is called.

     
  2. Fred Lee October 17, 2008 at 11:23 AM

    A CallBack? I have not tried it. I may attempt to execute the method. But, I think the real limitation is whether an instance can call dot destroy on itself.

     
  3. Steel October 17, 2008 at 11:26 AM
    This comment has been removed by the author.
  4. Steel October 17, 2008 at 11:27 AM
    This comment has been removed by the author.
  5. Steel October 17, 2008 at 11:28 AM

    Actually why not stick the logic in the before_destroy method so that the caller can just call destroy and your magic is performed and then destroyed.