我是Ruby on Rails的新手,并且遵循rubyonrails指南。我不知道我做错了什么。Ruby on Rails 5.8错误
Post_controller.rb
class PostsController < ApplicationController
def index
@posts = Post.all
end
def new
end
def create
@post = Post.new(post_params)
@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
我index.html.erb
<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>
我收到
Showing c:/Sites/blog/app/views/welcome/index.html.erb where line #9
raised:
undefined method `each' for nil:NilClass
Extracted source (around line #9):
<th>Text</th>
</tr>
<% @posts.each do |post| %>
<tr>
<td><%= post.title %></td>
<td><%= post.text %></td>
正如你可以看到在我的高清变量 “@posts” 错误索引与我的变量“@ posts.each do | post |”相关。不知道为什么这不起作用。
模型是否包含任何数据? – Nikola
我遵循rubyonrails指南并创建了后期模型 $ rails生成模型文章标题:字符串文本:文本 它创建了几个文件。其中之一是post.rb.它包含以下内容: class Post
先创建一个帖子,然后尝试显示它。 – Nikola