Check if record was just destroyed in rails
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?
Just do it:
record.destroyed?
Details are here ActiveRecord::Persistence
You can do this.
Record.exists?(record.id)
However that will do a hit on the database which isn't always 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
.
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!
destroy
ing 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.
While record.destroyed? works fine, and does return true or false, you can also DRY this up a little bit and create the if condition on the line you call destroy on in your controller.
record = Object.find(params[:id])
if record.destroy
... happy path
else
... sad path
end
Realize this post is a bit late in the game. But should anyone want to discuss this more, i'm game! Side note: I also had an after_destroy validation on my model and while it worked, a separate method for something like this seems like overkill ;)