0

I'm trying to display something like this on posts/index.html.erb

Post #1
  Comment #1 for Post #1
  Comment #2

Post #2
  Comment #1 for Post #2

etc.

It works fine if I go to /posts/1/comments/, /posts/2/comments/ etc

Since it's using the index file, there is no :post_id in the URL and it throws a nil error. The models use the appropriate have_many and belongs_to.

Here's part of routes.rb

resources :posts do
  resources :comments
end

resources :posts

Here's part of my posts_controller.rb

def index
@posts = Post.all
@comments = params[:post_id][:desc]

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @posts }
 end
end

Here's part of index.html.erb

<% @posts.each do |post| %>
  <tr>
    <td><%= post.title %></td>
    <td><%= link_to 'Show', post %></td>
    <td><%= link_to 'Edit', edit_post_path(post) %></td>
    <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<tr><td><%= @comments %></td></tr>
<% end %>
</table>

Thanks!

airlok
  • 425
  • 3
  • 14

1 Answers1

1

Well, since comments belongs_to a given post, you just need to have a separate loop in the view to iterate over each of the comments for a given post.

So take the @comments var out of your controller and index view, and do this in the index view instead where you currently have @comments:

<% for comment in post.comments %>
  <tr><td><%= comment.user_name %><%= comment.text %></td></tr>
<% end %>

I made the user_name and text attrs up of course you would use whatever is in your comment model.

ian.

ipd
  • 5,674
  • 3
  • 34
  • 49