我的Rails应用程序有很大的问题。我为我的功课创建了高级博客
我需要编辑我的评论,但我的网址返回此'/ posts / 4%2F12 / comments / 4 / edit'而不是/ posts / 4 / comments / 12 / edit
如果我自己正确输入URL,则可以访问有效的修改表单
您可以在这里看到我的代码
show.html.haml
.article
.container
.row
.col-lg-12
.cover-image{:style => "background-image: url('#{@post.photo_url}');"}
%h1.mt-4= @post.title
#{I18n.l(@post.created_at)}
%hr/
%p.lead= @post.content.html_safe
%hr/
.card.my-4
%h5.card-header Ajouter un commentaire :
.card-body
= render 'comments/form', comment: @post.comments.build
.media.mb-4
.media-body
- @post.comments.each do |comment|
%h5.mt-0= comment.content
%h5.mt-0= comment.user_name
%h2 Edit user
= link_to edit_post_comment_path([@post, comment]) do
%button.btn.btn-primary{:type => "button"} Primary
= link_to "Delete Comment", [@post, comment], method: :delete, data: { confirm: 'Are you sure?' }
comments_controller.rb
before_action :set_post, only: [:create]
def create
@comment = @post.comments.new(comment_params)
@comment.user_name = current_user.nickname
if @comment.save!
redirect_to @post
else
flash.now[:danger] = "error"
end
end
def edit
@post = Post.find(params[:post_id])
end
def destroy
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post)
end
private
def comment_params
params[:comment].permit(:content, :post_id)
end
def post_params
params.require(:comment).permit(:content)
end
def set_post
@post = Post.find(params[:post_id])
end
routes.rb
resources :users, only: :show
resources :posts do
resources :comments
end
root 'home#index'
root :to => redirect("/users/sign_in")
答案 0 :(得分:1)
您应该将两个参数传递给edit_post_comment_path
方法,而不是像这样传递数组:
edit_post_comment_path(@post, comment)
答案 1 :(得分:1)
代替
link_to edit_post_comment_path([@post, comment]) do
尝试
link_to edit_post_comment_path(@post, comment) do
或者
link_to [:edit, @post, comment] do
请参见https://guides.rubyonrails.org/routing.html#creating-paths-and-urls-from-objects
答案 2 :(得分:0)
也在
Comments Controller
中使用before_action进行评论
before_action :set_comment, only: [:show, :edit, :update, :destroy]
.....
.....
private
def set_comment
@comment = @post.comments.find(params[:id])
end
,然后在views / comments / show.html.haml
edit_post_comment_path(@post, @comment)
尝试一下...