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