ActiveRecord 'destroy' method returns a boolean value in Ruby on Rails?
Asked Answered
G

2

27

I am using Ruby on Rails 3 and I would like to know what type of return will have the following code:

@user.destroy

I need that to handle cases on success and fault in someway like this:

if @user.destroy
  puts "True"
else
  puts "false"
end

Is it possible? If so, how?

Goatsbeard answered 7/2, 2011 at 14:10 Comment(0)
A
43

You should try what you're asking before asking. What you've got there will work just fine.

If the destroy works, it will return the object (which will pass as true in an if statement) and if not, it will return false or raise an exception, depending on why it failed.

Augustine answered 7/2, 2011 at 14:30 Comment(2)
To clarify let's quote the docs: "If the before_destroy callback return false the action is cancelled and destroy returns false. " (edgeapi.rubyonrails.org/classes/ActiveRecord/…).Doug
I think you are being a little harsh. The official doc doesn't really say the return value for other failure path (e.g. from db or after_destroy callback), and it is hard to simulate one.Sugihara
L
19

It's possible. The destroy method returns the object that was destroyed; you could use destroyed? on this ActiveRecord object to check if the object is effectively destroyed:

if @user.destroyed?
  puts "True"
else
  puts "false"
end
Likker answered 7/2, 2011 at 14:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.