0
votes

I'm following the rails tutorial (http://tutorials.jumpstartlab.com/projects/blogger.html#blogger-2), making a simple blog. In one of the exercises, it asks for me to implement the destroy method for my Articles_Controller (articles is the model for the blog post structure).

I've implemented the delete function, but afterwards, when trying to redirect_to article_path(@article), it can't find the record (of course it was deleted). I'm wondering how to redirect_to the index page?

After deleting an article, I get the rails error page and:

error: ActiveRecord::RecordNotFound in ArticlesController#show 

my app/controllers/articles_controller.rb:

def destroy
  @article = Article.find(params[:id])
  flash.notice = "Article '#{@article.title}' destroyed."
  redirect_to article_path(@article)
  @article.destroy
end

The method as defined in ArticleController#show

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

2 Answers

0
votes

You can redirect to the index path with redirect_to articles_path

so:

def destroy
  begin
    @article = Article.find(params[:id])
    if @article.destroy
      redirect_to articles_path, notice: "Article '#{@article.title}' destroyed."
    else
      redirect_to article_path(@article), alert: "Article could not be destroyed."
    end
  rescue ActiveRecord::RecordNotFound
    redirect_to articles_path, alert: "Article with id '#{params[:id]}' not found"
  end
end
0
votes

If you want to redirect to the index page of your application. You could do something like this.

def destroy
   @article = Article.find(params[:id])
   @article.destroy
   flash.notice = "Article '#{@article.title}' destroyed"
   redirect_to root_index
end