Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Params[:id] returning nil for custom action

I'm trying to implement replying for comments. Along the way, I had to create a new action in the comments_controller in order to use AJAX to let the reply form show up without refreshing the page. The problem is when I carry out the code

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

Params[:id] is giving nil.

Some of my files

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

then

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

and

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

The same line Comment.find(params[:id]) works when I do this

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

But not for

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

I'm guessing it has something to do with my routes? Also as a side question, which may be related, when I'm making a route for a custom action when do I use get, post, delete, patch, etc.

like image 358
Jill Avatar asked Feb 12 '26 10:02

Jill


1 Answers

Please try adding member in your routes

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

When you don't add on: :member, the generated route will be /comments/:comment_id/reply and when you do, the route will be /comments/:id/reply.

like image 197
Ojash Avatar answered Feb 17 '26 12:02

Ojash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!