Reputation: 359
I am working through a Ruby on Rails tutorial for creating a blog and I have received this error when I go to bring up the page in my localhost:3000 address:
'undefined method `each' for nil:NilClass'
My Controller:
class PostsController < ApplicationController
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
def index
@posts = Post.all
end
end
My View File:
<h1>Listing posts</h1>
<table>
<tr>
<th>Title</th>
<th>Text</th>
</tr>
<% @posts.each do |post| %>
<tr>
<td><%= post.title %></td>
<td><%= post.text %></td>
</tr>
<% end %>
</table>
Can someone help me out?
Upvotes: 0
Views: 47
Reputation: 51191
Because your PostsController#index
method is private, so its code doesn't run when you enter /posts
, so @posts
instance variable remains nil
.
Move it to public section:
class PostsController < ApplicationController
def index
@posts = 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
Upvotes: 1