How to use Link_to with nested resources

fuco picture fuco · Apr 29, 2013 · Viewed 9.1k times · Source

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?

Answer

toch picture toch · Apr 29, 2013

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