我正在尝试添加删除帖子选项。我真的不知道我做错了什么,我之前从未遇到过这个错误。它一直告诉我没有路由匹配删除。可能是因为它认为删除按钮是用于删除用户而不是帖子?
No route matches [DELETE] "/users/***"
我的帖子视图代码
<div class="container">
<% for @p in @posts %>
<div class="row">
<div class="col-md-3">
<p><%= @p.content %></p>
<p><%= current_user.username %></p>
<%= link_to "delete", @p_path, method: :delete,
data: { confirm: "You sure?" } %>
</div>
</div>
<% end %>
</div>
<div class="container">
<div class="row">
<div class="col-md-5">
<%= render '/components/post_form' %>
</div>
</div>
</div>
控制器中的代码
class PostsController < ApplicationController
#new post
def new
@post = Post.new
end
#create post
def create
@post = Post.new(posts_params)
@post.user_id = current_user.id
respond_to do |f|
if (@post.save)
f.html {redirect_to "", notice: "Succesfully posted."}
else
f.html {redirect_to "", notice: "An error happened while submitting your post. Please try again."}
end
end
end
#show post
def show
if (User.find_by_username(params[:id]))
@post = params[:id]
end
end
#destroy post
def destroy
@post.destroy
redirect_to root_path
end
#private
private
def posts_params
params.require(:post).permit(:user_id, :content)
end
end
路线中的代码
Rails.application.routes.draw do
devise_for :users
# default page redirect
root 'pages#index'
#other pages
get 'home' => 'pages#home'
get '/users/:id' => 'pages#profile'
get 'explore' => 'pages#explore'
#form resources
resources :posts
end
答案 0 :(得分:0)
您没有@p_path
个实例变量。如果我没有弄错,你打算只使用@p
。请参阅以下
<div class="container">
<% for @p in @posts %>
<div class="row">
<div class="col-md-3">
<p><%= @p.content %></p>
<p><%= current_user.username %></p>
<%= link_to "delete", @p, method: :delete,
data: { confirm: "You sure?" } %>
</div>
</div>
<% end %>
</div>
...
...
<强>建议强>
请勿使用for @p in @posts
。只需使用for p in @posts
,因为p
几乎总是在视图文件中成为局部变量。你不需要一个实例变量。