我正在尝试使用rails创建一个简单的博客5.我的应用程序有一个帖子,用户,类别和评论模型。一切正常,但我不能让它工作编辑和销毁评论的行动。
这是虔诚的控制者
comments_controller.rb
Class CommentsController < ApplicationController
def new
@comment=Comment.new
@post=Post.find(params[:post_id])
end
def create
@post=Post.find(params[:post_id])
@comment=Comment.new(params.require(:comment).permit(:body))
@comment.user_id=current_user.id
@comment.post_id=@post.id
if @comment.save
redirect_to(post_path(@post))
else
render('new')
end
end
def edit
@post=Post.find(params[:post_id])
end
def update
end
def destroy
@post=Post.where(id: params[:post_id])
@comment=Comment.where(post_id: params[:post_id],id: params[:id] )
@comment.destroy(params[:post_id])
redirect_to(post_path(@post))
end
end
posts_controller.rb
class PostsController < ApplicationController
before_action(:post_find,only: [:show,:edit,:update,:destroy])
before_action(:authenticate_user!,except: [:index,:show])
before_action(:owner?,only: [:edit,:update,:destroy])
before_action(:find_categories,only: [:new,:create,:edit,:update])
def index
if params[:category].blank?
@posts=Post.all
else
@category_id=Category.find_by(name: params[:category]).id
@posts=Post.all.where(category_id: "#{@category_id}").order("created_at DESC")
end
end
def new
@post=Post.new
end
def create
@post=Post.new(post_params)
@post.user_id=current_user.id
@post.category_id=params[:category_id]
if @post.save
redirect_to(root_path)
else
render('new')
end
end
def show
end
def edit
end
def update
@post.category_id=params[:category_id]
if @post.update(post_params)
redirect_to(post_path(@post))
else
render('edit')
end
end
def destroy
@post.destroy
redirect_to(posts_path)
end
private
def post_params
params.require(:post).permit(:title,:body,:category,:category_id)
end
def post_find
@post=Post.find(params[:id])
end
def owner?
if user_signed_in?
if @post.user.id!=current_user.id
redirect_to(root_path)
end
end
end
def find_categories
@categories=Category.all.map{|c| [c.name,c.id]}
end
end
posts / show.html.erb(重要部分)
<h4>
Comments
<% if user_signed_in? %>
| <%= link_to("New comment",new_post_comment_path(@post)) %>
<% end %>
</h4>
<ul>
<% @post.comments.each do |f| %>
<li>
<%= f.body %> |
by <%= f.user.email %> |
<%= link_to("Delete",post_comment_path(f),method: :delete) %>
</li>
<% end %>
</ul>
任何想法我做错了什么?
答案 0 :(得分:1)
您正在传递comment_id
代替post_id
而您没有在 post_comment_path 链接中传递post_id
。
尝试更改link_to
删除操作,如下所示:
<%= link_to("Delete",post_comment_path(@post, f),method: :delete) %>
并且,由于您已经删除了评论,请从destroy函数中删除params[:post_id]
,如下所示:
def destroy
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to(post_path(@post))
end
详细了解路由和网址助手:http://guides.rubyonrails.org/routing.html#creating-paths-and-urls-from-objects
答案 1 :(得分:0)
将nested_scaffold gen用于另一个测试应用...从那里你可以了解嵌套资源。