0

我正在研究这个 Rails 教程:“ http://guides.rubyonrails.org/getting_started.html ”,然后我到了应该显示单个帖子(5.7)的标题和数据的部分并得到了一个当它应该显示数据时出错,所以我@post.inspect输入 /app/views/posts/show.html.erb 并且我得到了 nil,与列出所有帖子的索引页面相同,但我检查了数据在数据库中正确。这是我的控制器文件:

class PostsController < ApplicationController
def new
end

def create
  @post = Post.new(post_params.permit(:title, :text))

  @post.save
  redirect_to @post
end


private
  def post_params
    params.require(:post).permit(:title, :text)
  end

def show
  @post = Post.find(params[:id])
end
def index
  @posts = Post.all
end
end

错误:

NoMethodError in Posts#show
Showing /home/hiram/rails/meme/app/views/posts/show.html.erb where line #3 raised:

undefined method `title' for nil:NilClass
Extracted source (around line #3):
1 <p>
2 <strong>Title:</strong>
3 <%= @post.title %>
4 </p>
5
6 <p>

Rails.root: /home/hiram/rails/meme
4

1 回答 1

0

移动

private
  def post_params
    params.require(:post).permit(:title, :text)
  end

到文件末尾

"nil:NilClass 的未定义方法 `title'" Rails 指南教程

于 2013-08-02T17:19:38.407 回答