2011-07-27 50 views
3

如果用戶試圖從相冊中刪除最後一張照片,則不應該刪除它,並且應該向用戶顯示錯誤。Rails:如何防止刪除最後一個相關項目?

以下代碼的工作原理是它可以防止刪除,但錯誤消息永遠不會呈現給用戶,並且控制器會重定向,就好像操作已成功。

我哪裏錯了?

class Album < ActiveRecord::Base 
    has_many :photos 
    accepts_nested_attributes_for :photos, 
    :allow_destroy => true, :reject_if => :all_blank 
end 

class Photo < ActiveRecord::Base 
    belongs_to :album 
    before_destroy :do_not_delete_last_photo 

    def do_not_delete_last_photo 
    if album.photos.size == 1 
     errors.add(:base, 'Cannot delete the last photo') 
     return false 
    end 
    end 
end 

class AlbumsController < ApplicationController 
    def update 
    @album = Album.find(params[:id]) 
    if @album.update_attributes(params[:album]) 
     redirect_to albums_path, :notice => 'Album has been updated' 
    else 
     render :edit 
    end 
    end 
    # ... 
end 

回答

3

我可能是錯的,但我認爲你沒有得到的錯誤,因爲do_not_delete_last_photo方法不是驗證。

據我所知,rails不會在destroy上運行驗證。所以你可以使用異常。我還沒有使用它們,所以代碼就是我從文檔中得出的結果。

更改errors.addraise LastPhotoDeletionError, "Cannot delete the last photo"

我想,你應該創建一個類

LastPhotoDeleteionError < StandardError 
end 

,並把它放在last_photo_deletion_error.rb lib文件夾中。 之後,在控制器中你應該做

rescue_from YourErrorClass do |exception| 
    flash[:error] = "Cannot delete the last photo" # can't figure a way to access the message you set with `raise` 
    render :edit 
end 
相關問題