扶手:无法摧毁后(Rails: unable to destroy post)

2019-10-18 15:53发布

我建立基于Ruby on Rails的论坛应用程序。 我有破坏柱控制器行动的问题。 我的帖子控制器:

class PostsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_topic, only: :create

  def new
    @post = @topic.posts.new
  end

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

    if @post.save
      flash[:notice] = 'Post created successfully!'
      redirect_to(:back)
    else
      render 'shared/_post_form'
    end
  end

  def destroy
    @post = Post.find(params[:id])
    @post.destroy
    redirect_to(:back)
    flash[:error] = "Post was destroyed!"
  end

  private

  def set_topic
    @topic = Topic.find(params[:topic_id])
  end

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

这是我的路线:

  resources :contact_forms, only: [:new, :create]
  match '/contact', to: 'contact_forms#new',    via: 'get'
  root 'static_pages#home'

  resources :forums, only: [:index, :show] do
    resources :topics, except: :index
  end

  resources :topics, except: :index do 
    resources :posts
  end

  devise_for :users
  resources :users, only: :show

我去的话题show行为和我有联系删除帖子:

= link_to "Delete", topic_post_path(post.topic.forum.id, post.topic.id), method: :delete, data: {confirm: "You sure?"}, class: 'label alert

当我点击它,我有以下错误:

ActiveRecord::RecordNotFound in PostsController#destroy 
Couldn't find Post with id=46

有任何想法吗?

Answer 1:

你是不是传递post.id破坏链接。 试用:

= link_to "Delete", topic_post_path(post.topic.id, post.id), method: :delete, data: {confirm: "You sure?"}, class: 'label alert'

UPD:没有做到这一点更短的方式:

= link_to "Delete", [post.topic.id, post.id], method: :delete, data: {confirm: "You sure?"}, class: 'label alert'


文章来源: Rails: unable to destroy post