我是 Rails 新手并关注http://guides.rubyonrails.org/getting_started.html。我目前在第 5.8 节中,该节应列出我博客中 localhost:3000/posts 中的所有帖子,但我却收到一条消息:
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>
这是我的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
结尾
这是我的 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 %>
我一直在寻找,但一直无法找到答案!