Reputation: 207
I'm another Rails newbie and have followed the Ruby tutorial on creating a blog.
Each post has many comments and the comments belong to the posts.
I can see the comments in the individual blogs and have created a show link to show the individual comment.
What I'd really like to do is create an index page for comments which shows all of them. I created an index action in the comments controller:
def index
@title = "All comments"
@comments = Comment.all
end
And an accompanying index page,
<% @comments.each do |comment| %> Comment: <%= @comment.body %>
<% end %>
But I get an error:
undefined method `body' for nil:NilClass
My routes file:
resources :posts do resources :comments end
I'd really appreciate it if someone could point me in the right direction - I think my issue is that my comments are nested in the posts.
Thanks,
Bob
Upvotes: 0
Views: 1053
Reputation: 3529
So in your loop in the view file, you are iterating over the @comments
array, creating a comment
object for each of the comments in @comments
. As such, try
<% @comments.each do |comment| %> Comment: <%= comment.body %>
Upvotes: 1
Reputation: 20675
You should be using the comment
passed into the block:
<% @comments.each do |comment| %> Comment: <%= comment.body %>
You're currently calling @comment.body
, and @comment
is nil because it is undefined in your controller and elsewhere.
Upvotes: 1