ruby-on-rails - rails : How can I prevent the deletion of the last related item?

标签 ruby-on-rails ruby-on-rails-3

如果用户试图从相册中删除最后一张照片,则不应删除它,并且应该向用户显示错误。

以下代码的工作原理是它可以防止删除,但永远不会向用户显示错误消息,并且 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/

相关文章:

ruby-on-rails - rails : How to implement protect_from_forgery in Rails API mode

ruby-on-rails - Rails 如何使 Assets 过期?

ruby-on-rails - 将模块添加到测试类

ruby-on-rails - 显示Flash消息的最佳实践方法

ruby-on-rails-3 - 人性化轨道选择助手

ruby-on-rails - Rails 中的大小写不敏感

ruby-on-rails - 如何使用 Rails Clockwork gem 运行 rake 任务?

ruby-on-rails - Ransack,Postgres - 对具有不同 : true 的关联表中的列进行排序

ruby-on-rails-3 - 安装 rails-3 插件的问题 (Win7)

ruby - 如何使用 Fog (rubygem) 只启动/停止 aws ec2 实例,但不终止?