1

我正在构建基于 Ruby on Rails 的论坛应用程序。我在 Post Controller 中的销毁操作有问题。我的帖子控制器:

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

我去主题显示操作,我有删除帖子的链接:

= 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

有任何想法吗?

4

1 回答 1

2

您没有通过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'
于 2013-09-15T17:33:07.070 回答