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

发布于 2022-09-06 10:19:14 字数 379 浏览 17 评论 0

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

扭转时空 2022-09-13 10:19:14

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.

淡笑忘祈一世凡恋 2022-09-13 10:19:14

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文