将方法名称 destroy 更改为 delete in controller.rb in Ruby on rails,

Change the method name destroy to delete in controller.rb in Ruby on rails,

class ArticlesController < ApplicationController
    http_basic_authenticate_with name: "deba", password: "12345", except: [:index, :show]

    def index
        @articles = Article.all
    end

    def show
        @article = Article.find(params[:id])
    end

    def new
        @article = Article.new
    end

    def edit
        @article = Article.find(params[:id])
    end

    def create
        @article = Article.new(article_params)
        @article.save
        redirect_to @article
    end

    def update
        @article = Article.find(params[:id])

        if @article.update(article_params)
          redirect_to @article
        else
          render 'edit'
        end
    end

    def delete
        @article = Article.find(params[:id])
        @article.delete
        redirect_to articles_path
      end

    private
    def article_params
        params.require(:article).permit(:title, :text)
    end
end

我试过这样做,但没有删除项目。如果我将删除更改为销毁它工作正常但我必须更改默认方法名称

不确定您指向哪个默认方法名称,但控制器操作的默认名称是 destroy 而不是 delete。如果您希望更改操作的名称,您可以添加一个新路由,将用户带到删除操作并使用它代替默认的销毁操作。

在操作中,您正在尝试执行 @article.delete,这是有效的,但建议始终使用 destroy,因为 delete 方法只会 运行 SQL DELETE 语句和 运行 没有回调。 destroy 将始终 运行 回调。

更多信息在这里:

Difference between Destroy and Delete

Why the Ruby on Rails action "destroy" is not named "delete"?

如果您真的想将 DELETE /articles/:id 路由到控制器中的 delete 方法,您可以通过自定义路由来实现:

Rails.application.routes.draw do
  resources :articles, except: :destroy do
    delete '/', on: :member, action: :delete # but why?
  end
end

您也可以只为方法设置别名而不是修改路由:

class ArticlesController < ApplicationController 
  # ...
  def delete
    @article = Article.find(params[:id])
    @article.delete # you should be using destroy
    redirect_to articles_path
  end

  alias delete destroy

  # ...
end 

然而这完全没有意义。遵循约定,将时间花在提高工作效率和编写可维护的代码上。