0

Problem: Looking for the right comment that belongs to a post

I am trying to implement a "like" function (just like on facebook) for comments on a specific post. I've already implemented the same function for my posts, but "pointing at the right comment" is giving me hard time. To clarify, my "like" function results in the following GET call:

http://localhost:3000/posts/11/comments/4/like

But it's actually supposed to call

/posts/4/comments/11/like

I checked my route, and it seems right to me

like_post_comment GET    /posts/:post_id/comments/:id/like(.:format)

So I guess the problem lies in the controller.

In the beginning of my like action in comments_controller, I have

def like
    @post = Post.find(params[:post_id])
    @comment = @post.comments.find(params[:comment])

I think this must be wrong, but I'm not sure why or how to fix it. The other actions set local variables @post and @comment in a similar way, but they do the job correctly.

def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment])

def destroy
    @post = Post.find(params[:post_id])
    @comment = @post.comments.find(params[:comment])

How I render my link to comment

<td><b><%= link_to 'like', like_post_comment_path(comment) %></b></td>
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Maximus S
  • 10,759
  • 19
  • 75
  • 154

3 Answers3

1

call it like this

<%= link_to 'like', like_post_comment_path(@post, comment) %>

where @post is the current post object

Super Engineer
  • 1,966
  • 1
  • 13
  • 21
1

Replace your link from

<td><b><%= link_to 'like', like_post_comment_path(comment) %></b></td>

to

<td><b><%= link_to 'like', like_post_comment_path(@post, comment) %></b></td>

And replace your like action in controller with

def like
  @post = Post.find(params[:post_id])
  @comment = @post.comments.find(params[:id])
  # ...
end
Hck
  • 9,087
  • 2
  • 30
  • 25
0

this:

/posts/:post_id/comments/:id/like(.:format)

tells me that your post is identified by the post_id param, and your comment is identified by the id param. therefore, your like method should look like this:

def like
  @post = Post.find(params[:post_id])
  @comment = @post.comments.find(params[:id])
ChuckE
  • 5,610
  • 4
  • 31
  • 59
  • still, post_id and id(comment) are switched. – Maximus S Nov 21 '12 at 08:14
  • in your url, maybe. that has to do with the way you are building that url. probably you are using an helper called like_post_comment_url. Call it like this: like_post_comment_url(@comment, :post_id => @post.id) or the closest variant in your case. – ChuckE Nov 21 '12 at 08:18
  • I've just seen your edit. Where does the post_id comes in your case, if you are only passing one argument to the helper? are you using nested routes? If not, maybe you should (it fits your example) – ChuckE Nov 21 '12 at 08:19