Rails在删除时无法获取before_destroy进行调用

时间:2013-11-26 17:37:37

标签: ruby-on-rails

我已经有一段时间了,需要一个更聪明的人的意见。我正在尝试检查我的数据库中的密码与用户输入的密码匹配,以便删除记录。我相信我应该在模型中这样做,我正在重构使用before_destroy方法。但是当我点击我创建的删除按钮时,我甚至无法执行before_destroy方法。控制器确实执行了destroy方法。

查看

<%= button_to('Destroy', @dish, method: "delete") %>

模型 - puts passcode_check?永远不会从我看到的内容中调用

class Dish < ActiveRecord::Base
   before_destroy :passcode_check?
   validates :username, presence: true
   validates :passcode, presence: true
   validates :guests, numericality: { only_integer: true, greater_than_or_equal_to: 0 }

  private

  def passcode_check?
    puts "passcode_check?"
     if @dish.passcode != params[:pass]
       @dish.errors.add( :base, 'Unable to delete record; Reason: Passcodes did not match.')
       return false
     else
       @dish.errors.add( :base, 'test.')
       return false
     end
   end 
end

控制器 - 我希望在模型中验证这种方法的涌入

  def destroy
    if @dish.passcode == params[:pass]
      @dish.destroy unless @dish.errors
      respond_to do |format|
        format.html { redirect_to dishes_url, notice: 'Record delete.' }
        format.json { head :no_content }
      end
    else
      respond_to do |format|
        format.html { redirect_to @dish, action: 'show', notice: 'Unable to delete record; Reason: Passcodes did not match.' }
        format.json { render json: @dish.errors, status: :unprocessable_entity  }
      end
    end
  end

1 个答案:

答案 0 :(得分:1)

在您的控制器中,您使用@dish.errors,它将始终返回ActiveModel::Errors个对象,因此非常真实。所以unless @dish.errors语句修饰符永远不会让@dish.destroy运行,因此你的回调也不会。将其更改为:

@dish.destroy if @dish.errors.empty?

那应该是它。虽然检查错误没有多大意义,因为甚至没有验证。只需调用@dish.destroy并让你的before_destroy回调通过返回false来暂停删除,相反,通过返回true来删除。