11

I am a totally newbie in Rails.

I have created a web application, I can access through /posts/123/comments/ or /posts/123/comments/new, but i don't know how to use link_to in the index view to show a concrete comment, when i try to link it, appears "no route" or "undefined symbol".

I have a nested have_many relation between posts and comments defined in the models and in the routes.rb and post_comments GET /posts/:post_id/sensors(.:format) comments#index appears when I execute rake routes.

How I can do it?

toch
  • 3,905
  • 2
  • 25
  • 34
fuco
  • 223
  • 3
  • 11

4 Answers4

12

If you have defined nested resources (and of course your models Comment and Post are associated)

resources :posts do
 resources :comments
end

You can link a comment as following

<!-- /posts/:post_id/comments/:id -->
<%= link_to 'Show', [@comment.post, @comment] %>

I've written a full example of nested resources in a past blog post

toch
  • 3,905
  • 2
  • 25
  • 34
  • I have changed my code to <% @posts.each do |item| %> <%= item.nombre %> <%= item.info %> <%= link_to 'Show', [@comment.post, @comment] %> <% end %> and it doesnt run... appear a undefined method post. How can I do it? Thanks! – fuco Apr 29 '13 at 11:59
  • That's probably because your `Comment` model is not associated to `Post`. You should have `belongs_to :post` in your `Comment` model. If not, it's normal it's undefined. You can also replace `@comment.post` with the `Post` object containing the comment (probably `item` in your case). – toch Apr 29 '13 at 12:04
  • That's not working for me: it complains that `post_comment_path` is undefined (the routing that shows in `rake routes` is `post_comments`, plural) – digitig Jul 14 '14 at 16:14
8

After trying all of the answers it didnt completely work, but i found a way to resolve it. In a first moment, I used

post_comments_url(@post,comment)

where comment is the item inside a @post.each.

It generates a "strange" route, using . instead / like "post/34/comments.2", i fixed it using the singular form:

post_comment_url(@post,comment)

Thanks for helping!

fuco
  • 223
  • 3
  • 11
1

Get method name from the first column of

   rake routes

And pass the ids accordingly. And of course suffix the method name with _path ir _url To know more, visit the Rails guide

Aditya Kapoor
  • 1,542
  • 10
  • 13
Shairon Toledo
  • 2,024
  • 16
  • 18
0

Additionally to the answer of toch, you can debug your link_to call with help of the Rails console.

For this, you need to load the view helpers in the console:

irb(main):001:0> include ActionView::Helpers::UrlHelper
=> Object
irb(main):002:0> helper.link_to "posts", app.posts_path
=> "<a href=\"/posts\">foo</a>"

Another tool, similar to Rake routes for route debugging is: https://github.com/schneems/sextant

poseid
  • 6,986
  • 10
  • 48
  • 78