I'm following the tutorial found here. It's simple, and I've followed the instructions exactly to step 6.7. At this point, I get the error
undefined method `each' for nil:NilClass
when I try to access index.html.erb on the rails server.
I know the database is working fine, because I can do everything mentioned in step 6.3, create new posts and show/edit/destroy them with absolutely no problems.
Specifically, the issue is with the line
<% @posts.each do |post| %>
and it's essentially claiming that @posts
is nil.
I appreciate any help for this ROR newbie! Thanks.
index.html.erb
<h1>Hello, Rails!</h1>
<table>
<tr>
<th>Name</th>
<th>Title</th>
<th>Content</th>
<th></th>
<th></th>
<th></th>
</tr>
<% @posts.each do |post| %>
<tr>
<td><%= post.name %></td>
<td><%= post.title %></td>
<td><%= post.content %></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>
<% end %>
</table>
<br />
<%= link_to "My Blog", posts_path %>
posts_controller.rb
class PostsController < ApplicationController
# GET /posts
# GET /posts.json
def index
@posts = Post.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @posts }
end
end
In order for the views
to work fine in Rails they must be inside the correct directory. This is one of the many implementations of the so called "Convention over Configuration" that Rails loves.
So, if you have a method index
and this method is inside a controller named PostsController
, you must have a view named index
inside the directory views/posts/
. This way, Rails will know that it have to render this view when a get to this method is processed.
About a good tutorial, I would recommend this one. It is extense and covers a lot of things that are not just related to Rails itself, like deploying on Heroku and a little CSS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With