如果用户试图从相册中删除最后一张照片,则不应删除它,并且应该向用户显示错误。
以下代码的工作原理是它可以防止删除,但永远不会向用户显示错误消息,并且 Controller 会重定向,就好像操作已成功一样。
我哪里错了?
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
最佳答案
我可能是错的,但我认为你没有得到错误,因为 do_not_delete_last_photo
方法不是验证。
据我所知,rails 不会在 destroy
上运行验证。因此,您可以使用异常。我还没有使用过它们,所以代码正是我从文档中得到的。
将 errors.add
更改为 raise LastPhotoDeletionError, "Cannot delete the last photo"
我想,你应该创建类
LastPhotoDeleteionError < StandardError
end
并将其放入lib文件夹中的last_photo_deletion_error.rb中。 之后,在 Controller 中你应该做
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
关于ruby-on-rails - rails : How can I prevent the deletion of the last related item?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6842013/