I'm coding a simple blog with posts and I can't seem to be able to get the code right for going back to the index page after "destroying" a post. I'm following this tutorial and I'm stuck around minute 14 Tutorial I'm working with ruby 3.0.3 and Rails 7.0.3, the error I'm getting is the following: Error
Below are the relevant pieces of code:
Controller
class PostsController < ApplicationController before_action :find_post, only: [:show, :edit, :update, :destroy] def index end def new @post = Post.new end def create @post = Post.new post_params if @post.save redirect_to @post, notice: "post has been saved" else render 'new', notice: "Post could NOT be saved" end end def show end def edit end def update if @post.update post_params redirect_to @post, notice: "Your article has been updated" else render 'edit' end end def destroy @post.destroy respond_to do posts_path end end private def post_params params.require(:post).permit(:title, :content) end def find_post @post = Post.find(params[:id]) end end
Show (view)
<%= @post.title %><br> <%= @post.content %> <br> <br> <%= link_to "Edit", edit_post_path(@post) %> <%= link_to "Delete", post_path(@post), data: { :turbo_method => :delete, :turbo_confirm => 'Are you sure?'} %>
Routes
Rails.application.routes.draw do resources :posts end
Migration
class CreatePosts < ActiveRecord::Migration[7.0] def change create_table :posts do |t| t.string :title t.text :content t.timestamps end end end
I would deeply appreciate any help.
CodePudding user response:
# DELETE /posts/1
def destroy
@post.destroy
redirect_to posts_url, notice: "Post was successfully destroyed."
end
This destroy method works with button_to
:
<%= button_to "Destroy post", post_path(@post), method: :delete %>
If you want to use link_to
:
<%= link_to "Destroy post", post_path(@post), data: { turbo_method: :delete } %>
redirect status has to be changed to status: :see_other
:
# DELETE /posts/1
def destroy
@post.destroy
redirect_to posts_url, status: :see_other, notice: "Post was successfully destroyed."
end
Turbo DELETE request work in progress: https://github.com/hotwired/turbo-rails/issues/259
CodePudding user response:
When you didn't find a record, is no way to destroy it. Rewrite post finder to:
def find_post
@post = Post.find_by(id: params[:id])
end
I replaced respond_to
with redirect_to
, but it is not a principal:
def destroy
@post.destroy
ensure
redirect_to posts_path
end
CodePudding user response:
The above error seems to have been fixed with
def destroy
@post.destroy
ensure
redirect_to posts_path
end
Now I'm getting a different error referring to my show page: