Carrein
Carrein

Reputation: 3361

Cannot implement delete in Rails controller

I'm following this tutorial to built a simple blogger side.

However, I am unable to implement the delete function as shown by the tutorial.

The steps given are as follows:

Let’s define the destroy method in our ArticlesController so it:

  • Uses params[:id] to find the article in the database

  • Calls .destroy on that object

  • Redirects to the articles index page

Do that now on your own and test it.

This is my code:

class ArticlesController < ApplicationController
    include ArticlesHelper

    def index
        @articles = Article.all
    end

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

    def new
        @article = Article.new
    end

    def create
        @article = Article.new(article_params)
        @article.save
        flash.notice = "Article '#{@article.title}' Created!"
        redirect_to article_path(@article) 
    end

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

show.html.erb

<h1><%= @article.title %></h1>
<p><%= @article.body %></p>
<%= link_to "<< Back to Articles List", articles_path %>
<%= link_to "delete", article_path(@article), method: :delete %>

article_helper.rb

module ArticlesHelper

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

end

I have browsed through other solutions online but I don't see any code which I might have missed out.

In my case, clicking on the delete link only results in the page refreshing.

Upvotes: 1

Views: 131

Answers (2)

Carrein
Carrein

Reputation: 3361

I figured out the issue:

The setup was running on Windows. I applied a fix previously as the page would not load.

This fix caused the error here :

ActionController::RoutingError (No route matches [GET] "/javascripts/default.js"):

The way to fix this is to undo the previous changes above and follow the fix here.

Apparently, coffee-script-source 1.9 and above does not work on Windows.

Upvotes: 1

Simple Lime
Simple Lime

Reputation: 11035

private methods in controllers are not accessible outside the controller, even to routes. So you'll never be able to route to destroy or article_params in your current code. If you move your destroy method above the private keyword, should fix things.

Upvotes: 2

Related Questions