开发者

Rails 3 - how to make own error handler

could anyone help me, please, how to make my own error handler for example for the situation, when I am trying to destroy the item from database, that doesn't exist (delete item with don't exist ID)?

I tried to search on google, but I still 开发者_C百科haven't something, what works.


I guess you will never read this, but it can help others. You have a problem with .find cause it raise an exception when your id is wrong.

You have 3 ways to manage it.

You can catch the exception with a rescue. But that's not the best way.

You can check if your id exists, you have few ways to do this way. (count for example). But that's not the best way, cause you have 2 queries.

Or you can use find_by_id. This does not raise an exception, and return nil when your object does not exist. You only have to check about the result.


your_item = YourModel.find_by_id(non_existent_id) # returns nil

# PS: YourModel.find(non_existent_id) would raise exception

if your_item
  your_item.destroy
  flash[:notice] = "Deleted item with id #{non_existent_id}"
else
  flash[:error] = "Cannot find item with id #{non_existent_id}"
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜