我正在尝试回复评论。在此过程中,我不得不在comments_controller中创建一个新动作,以便使用AJAX让回复表单显示而不刷新页面。问题是当我执行代码时
#routes.rb
resources :comments, :only => [:create, :destroy] do
get :reply
end
Params [:id]给出nil。
我的一些文件
#_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
和
= link_to "×", comment_path(comment), :method => :delete, :remote => true, :confirm => "Are you sure you want to remove this comment?", :disable_with => "×", :class => 'close'
同一行Comment.find(params [:id])在我这样做时起作用
%p= link_to "Reply", comment_reply_path(comment), :method => :get, :remote => true
但不适用于
<div class="col-xs-1 col-md-3 col-lg-6">
我猜它与我的路线有关?另外,作为一个可能相关的问题,当我为自定义操作制作路线时,我何时使用get,post,delete,patch等。
答案 0 :(得分:3)
请尝试在路线中添加会员
#routes.rb
resources :comments, :only => [:create, :destroy] do
get :reply, on: :member
end
如果您不添加on: :member
,生成的路线将为/comments/:comment_id/reply
,当您执行此操作时,路线将为/comments/:id/reply
。
答案 1 :(得分:0)
如果您希望回复传入ID,则需要提及会员。
#routes.rb
resources :comments, :only => [:create, :destroy] do
member do
get :reply
end
end