Params[:id] 为自定义操作返回 nil

Params[:id] returning nil for custom action

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

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

参数[:id] 为零。

我的一些文件

#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 等

请尝试在您的路由中添加成员

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

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

如果你希望回复传递一个id,你需要提到成员。

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