Rails 删除后路径被分配给 GET 方法而不是 DELETE

问题描述 投票:0回答:1

在我关联评论和帖子后,post_delete_path 在调用时开始发送 GET 请求而不是删除请求,显示以下错误:

routes.erb 文件:

Rails.application.routes.draw do
  #get 'posts/index'
  resources :posts do
    resources :comments, only: [:destroy, :create]
  end

  get '/delete_post', to: 'posts#destroy'

  resources :likes, only: [:destroy, :create]

  resources :sessions, only: [:create, :destroy]
  get 'sessions/new'
  get 'sing_in', to: 'sessions#new'
  get 'sign_out', to: 'sessions#destroy'

  resources :users, only: [:create, :destroy]
  get 'users/new'
  get '/register', to: 'users#new'

  root 'posts#index'
end

帖子控制器:

class PostsController < ApplicationController

  before_action :ensure_user
  before_action :correct_user, only: [:edit, :update, :destroy]

  def index
    @posts = Post.all.order("created_at DESC")
  end

  def show
    @post = Post.find(params[:id])
  end


  def new
    @post = current_user.posts.new
  end


  def create
    @post = current_user.posts.new(post_params)

    if @post.save
      redirect_to post_url(@post)
    else
      render 'new', notice: "Couldn't create the post!"
    end

  end

  def edit
    @post = set_post
  end

  def update
    @post = current_user.posts.find(params[:id])

    if @post.update(post_params)
      redirect_to post_url(@post)
    else
      redirect_to post_url(@post), notice: "Couldn't update the post!"
    end
  end


  def destroy
    @post = current_user.posts.find([params[:id]])

    if @post.destroy
      redirect_to posts_path, notice: "Post has been deleted!"
    else
      redirect_to post_url(@post), notice: "Couldn't delete the post!"
    end
  end


  private

  def correct_user
    @post = current_user.posts.find_by(id: params[:id])
    redirect_to root_path, notice: "You are not authorized to edit this post!" if @post.nil?
  end

  def set_post
    return Post.find(params[:id])
  end

  def post_params
    params.require(:post).permit(:title, :content)
  end


end

帖子视图中显示文件中的删除按钮:

<%= button_to 'Delete', delete_post_path(@post), method: :delete %>

即使在路由文件中指定了它,也不会显示使用 DELETE 请求删除帖子的路由: enter image description here

我尝试在帖子资源下的路由中指定删除路径,但它使用 GET 方法而不是 DELETE 显示新路径。

resources :posts do
    resources :comments, only: [:destroy, :create]
    get '/post_delete', to: 'posts#destroy'
end
resources :posts do
   resources :comments, only: [:destroy, :create]
end
get '/post_delete', to: 'posts#destroy'

另外,我尝试在button_to和link_to之间切换,尽管这没有帮助。

ruby-on-rails routes nested-routes
1个回答
0
投票

我不确定我是否理解了这一点,您正在输入

get "/a/path", to: "controller#action"
并想知道 为什么要创建 GET 路由

你会踢自己的:

delete '/post_delete', to: 'posts#destroy'

但这里真正的问题是为什么你不使用

resources :posts
中的删除路由?然后你只需使用:

button_to 'Delete', @post, method: :delete
© www.soinside.com 2019 - 2024. All rights reserved.