直接上代码:
def destroy
begin
@user.destroy
flash[:notice] = "User #{@user.name} deleted"
if User.count.zero? # 1
raise 'cant delete last user' # 2
end # 3
rescue StandardError => e
flash[:notice] = e.message
end
respond_to do |format|
format.html { redirect_to users_url }
format.json { head :no_content }
end
end
class User < ActiveRecord::Base
after_destroy :ensure_an_admin_remains # 4
validates :name, presence: true, uniqueness: true
has_secure_password
private
def ensure_an_admin_remains
if User.count.zero?
raise "Cant delete last user"
end
end
end
代码 1 2 3 是我后加上的,我的问题是,如果我不用 4 这里的 hook, 使用 1 2 3 做一个判断为什么不行?