gpt4 book ai didi

ruby-on-rails - 参数[:id] returning nil for custom action

转载 作者:行者123 更新时间:2023-12-02 04:35:19 24 4
gpt4 key购买 nike

我正在尝试实现评论回复。在此过程中,我必须在 comments_controller 中创建一个新操作,以便使用 AJAX 让回复表单在不刷新页面的情况下显示。问题是当我执行代码时

@comment = Comment.find(params[:id])

Params[:id] 给出 nil。

我的一些文件

#routes.rb
resources :comments, :only => [:create, :destroy] do
get :reply
end

然后

#_comment.haml
%div.comment{ :id => "comment-#{comment.id}" }
%hr
= link_to "×", comment_path(comment), :method => :delete, :remote => true, :confirm => "Are you sure you want to remove this comment?", :disable_with => "×", :class => 'close'
%h4
= comment.user.first_name
%small= comment.updated_at
%p= comment.body
%p= link_to "Reply", comment_reply_path(comment), :method => :get, :remote => true

#comments_controller.rb
def reply
@comment = Comment.find(params[:id])
respond_to do |format|
format.js
end
end

当我这样做时,同一行 Comment.find(params[:id]) 有效

= link_to "×", comment_path(comment), :method => :delete, :remote => true, :confirm => "Are you sure you want to remove this comment?", :disable_with => "×", :class => 'close'

但不适合

%p= link_to "Reply", comment_reply_path(comment), :method => :get, :remote => true

我猜这与我的路线有关?另外,作为一个可能相关的附带问题,当我为自定义操作制定路线时,何时使用 get、post、delete、patch 等。

最佳答案

请尝试在您的 route 添加成员

#routes.rb
resources :comments, :only => [:create, :destroy] do
get :reply, on: :member
end

当你不添加on: :member时,生成的路由将为/comments/:comment_id/reply,当你添加时,生成的路由将为/comments/:id/reply.

关于ruby-on-rails - 参数[:id] returning nil for custom action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32109483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com