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

I have tried to do like this, but it's not deleting the item. If i change the delete to destroy it is working fine but I have to change the default method name

2 answers

  • answered 2022-05-04 10:28 Deepesh

    Not sure which default method name you are pointing to but the default name for the controller action is destroy and not delete. If you wish to change the name of the action you can add a new route that takes the user to the delete action and use it instead of the default destroy action.

    Inside the action, you are trying to do @article.delete which is valid but would suggest always using destroy instead as the delete method will just run the SQL DELETE statement and run no callbacks. destroy will always run the callbacks.

    More information here:

    Difference between Destroy and Delete

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

  • answered 2022-05-05 08:15 max

    If you REALLY want to route DELETE /articles/:id to the delete method in your controller you can do it by customizing your routes:

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

    You could also just alias the method instead of modifying your routes:

    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 
    

    However this is utterly pointless. Follow the conventions and spend your time being productive and writing maintainable code instead.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum