【问题标题】:'Delete' action occurring twice?“删除”动作发生两次?
【发布时间】:2011-07-05 03:27:56
【问题描述】:

我的文件控制器的删除操作有一个奇怪的情况。

Started GET "/files/35/delete" for 127.0.0.1 at 2011-02-27 01:13:51 -0500
Processing by FilesController#delete as HTML
Parameters: {"id"=>"35"}
SQL (0.3ms)  DELETE FROM `files` WHERE (`files`.`id` = 35)
SQL (0.7ms)  COMMIT
Redirected to http://localhost:3000/files
Completed 302 Found in 713ms

Started GET "/files/35/delete" for 127.0.0.1 at 2011-02-27 01:13:52 -0500
Processing by FilesController#delete as HTML
Parameters: {"id"=>"35"}
...leads to error

控制器动作:

@file = @company.files.where("id = ?", params[:id]).first
@file.destroy
flash[:notice] = "Your file was deleted successfully."
redirect_to files_url

路线:

resources :files do
  member do
    get 'delete_ask'
    get 'delete'
  end
end

你知道为什么会这样吗?

【问题讨论】:

    标签: ruby-on-rails model-view-controller ruby-on-rails-3 controller routes


    【解决方案1】:

    我怀疑这是由于重复提交请求而发生的。尝试在客户端通过 javascript 或在服务器端防止双重提交(这将需要比客户端更多的努力,但更健壮)。

    【讨论】:

      【解决方案2】:
      @file = @company.files.where("id = ?", params[:id]).first
      if @file
          @file.destroy
          flash[:notice] = "Your file was deleted successfully."
      else
          #file was deleted
          flash[:notice] = "Patience: you only need to press delete once" 
      end
      redirect_to files_url
      

      您可以从错误中rescue

      @file = @company.files.where("id = ?", params[:id]).first
          @file.destroy
          flash[:notice] = "Your file was deleted successfully.
      #rescue from error
      rescue 
          flash[:notice] = "Patience: you only need to press delete once" 
          redirect_to files_url
      

      【讨论】:

        猜你喜欢
        • 2020-05-25
        • 2021-02-11
        • 1970-01-01
        • 1970-01-01
        • 2015-05-17
        • 1970-01-01
        • 2014-01-19
        • 1970-01-01
        • 2023-02-03
        相关资源
        最近更新 更多