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

吃可爱长大的小学妹 提交于 2019-12-10 00:42:40

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/4922233/activerecord-destroy-method-returns-a-boolean-value-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!