dannymcc
dannymcc

Reputation: 3824

Linking from owner to child records in Rails 3?

I know this is a really simple question, but I've gone completely blank! I'm reading through the Rails guides and looking at the getting started section. The following code is displaying all comments that belong to the current Post:

<h2>Comments</h2>
<% @post.comments.each do |comment| %>
 <p>
  <b>Commenter:</b>
  <%= comment.commenter %>
 </p>

<p>
<b>Comment:</b>
<%= comment.body %>
</p>
<% end %>

What is the simplest way of linking to each individual comment? For reference the page I am looking at is http://guides.rubyonrails.org/getting_started.html

The models are as follows:

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
end

Upvotes: 0

Views: 70

Answers (2)

gabitzish
gabitzish

Reputation: 9691

You should take a look to your routes, and see what's the path to an individual comment.

It should be something like : comment_path(comment) or post_comment(@post, comment)

You will link it with <%= link_to "View comment", comment_path(comment) %>

Upvotes: 1

rjz
rjz

Reputation: 16510

Rails will try to create route helpers to assist you in this. You can get a full list by running rake routes, but there are good odds that the one you'll be looking for is named comment_path:

<% @post.comments.each do |comment| %>
  <%= link_to 'Click to view comment', comment_path(comment) %>
<% end %>

For reference, check out the Rails Routing Guide.

Upvotes: 1

Related Questions