views:

645

answers:

5

So there is

record.new_record?

To check if something is new

I need to check if something is on it's way out.

record = some_magic
record.destroy
record.is_destroyed? # => true

Something like that. I know destroying freezes the object, so frozen? sort of works, but is there something explicitly for this task?

A: 

Without knowing more of the logic of your app, I think that frozen? is your best bet.

Failing that, you could certainly add a "destroyed" attribute to your models that you trigger in the callbacks and that could be checked against if you want a more precise solution.

Mike Buckbee
+1  A: 

destroying an object doesn't return anything other than a call to freeze (as far as I know) so I think frozen? is your best bet. Your other option is to rescue from ActiveRecord::RecordNotFound if you did something like record.reload.

I think Mike's tactic above could be best, or you could write a wrapper for these cases mentioned if you want to start 'making assumptions'.

Cheers.

theIV
I currently just check frozen?, but really I can load something and freeze it for some other purpose, and it would be a lie then...In the current situation, frozen? works fine, but I don't want to rely on it long term.
Daniel Huckstep
+6  A: 

You can do this.

Record.exists?(record)

However that will do a hit on the database which isn't really necessary. The only other solution I know is to do a callback as theIV mentioned.

attr_accessor :destroyed
after_destroy :mark_as_destroyed
def mark_as_destroyed
  self.destroyed = true
end

And then check record.destroyed.

ryanb
I think some context is helpful here. It depends on why you want to know if an object has been destroyed. If you're doing it as part of a unit test, then the extra hit against the database is fine. If you're doing it as part of the app, then going the second route might be a better bet.
jerhinesmith
+3  A: 

This is coming very soon. In the latest Riding Rails post, it says this:

And finally, it's not necessarily BugMash-related, but José Valim - among dozens of other commits - added model.destroyed?. This nifty method will return true only if the instance you're currently looking at has been successfully destroyed.

So there you go. Coming soon!

Steve Klabnik
A: 

Just do it:

record.destroyed?

Details here ActiveRecord::Base

Voldy