我正在构建基于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
有什么想法吗?
答案 0 :(得分: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'