【发布时间】:2014-05-21 08:03:22
【问题描述】:
albums_controller.rb:
lass AlbumsController < ApplicationController
before_action :set_album, only: [:show, :edit, :update, :destroy]
def destroy
if @album.destroy
redirect_to albums_url, notice: 'Album was successfully destroyed.'
else
redirect_to albums_url, error: 'Album destroy failed.' # _DEST_
end
end
private
def set_album
@album = Album.find(params[:id]) # _FIND_
end
end
我想捕获 Album.find() 的异常。根据this 我补充说:
rescue_from Exception, with: :flash_error
# private
def flash_error
flash_message :error, 'Something went wrong..' # _FLASH_
end
我将上面的一些部分标记为_FIND_、_FLASH_、_DEST_,我想按顺序浏览所有这些部分。我试图删除不存在的专辑来触发它。我得到了带有专辑 URL 的空白页面/(:id)(我试图删除的那个),所以我想我停留在 _FLASH_ 部分。
我应该怎么做才能调用destroy 操作(我的意思是原来的调用为rescue_form,因为它也可以捕获其他控制器操作的其他异常)。以及如何获得比Something went wrong 更好的消息?
主要目标是重定向到正确的页面(在_DEST_ 指定),所以也许有一些更好的方法。
【问题讨论】:
-
尝试使用
rescue_from ActiveRecord::RecordNotFound, with: :rescue_action -
变化不大,还是没有继续
_DEST_
标签: ruby-on-rails