Reputation: 53
I'm new to rails and following http://guides.rubyonrails.org/getting_started.html. I'm currently on section 5.8 which should list all the posts in my blog at localhost:3000/posts, but am instead getting a message:
NoMethodError in Posts#index
Showing /Users/sw/Code/blog/app/views/posts/index.html.erb where line #9 raised:
undefined method `each' for nil:NilClass
Extracted source (around line #9):
<% @posts.each do |post| %>
<tr>
<td><%= post.title %></td>
<td><%= post.text %></td>
Here's my posts_controller.rb:
class PostsController < ApplicationController
def index
@post = Post.all
end
def new
end
def create
@post = Post.new(params[:post].permit(:title, :text))
@post.save
redirect_to @post
end
def show
@post = Post.find(params[:id])
end
private
def post_params
params.require(:post).permit(:title, :text)
end
end
And here's my index.html.erb:
<table>
<tr>
<th>Title</th>
<th>Text</th>
</tr>
<% @posts.each do |post| %>
<tr>
<td><%= post.title %></td>
<td><%= post.text %></td>
</tr>
<% end %>
I've been searching all over and haven't been able to find an answer!
Upvotes: 2
Views: 4364
Reputation: 10198
You are looping through a variable @posts
, but in your index you are assigning a variable @post
.
Thus, in your posts_controller.rb
replace
def index
@post = Post.all
end
with
def index
@posts = Post.all
end
Upvotes: 4