遇到错误 "NoMethodError in Posts#show"

Encountered error "NoMethodError in Posts#show"

我是 ruby rails windows 的新人。我正在关注一些 guide through youtube,但遇到错误

问题:<%= @post.item %>的一部分,@post应该填什么?是我的方法还是我另一个视图中的字段名称?

"NoMethodError in Posts#show undefined method `item' for nil:NilClass Extracted source (around line #2): 1 2 <%= @post.item %> # the error indicates here 3 4 5 Submitted:<%= time_ago_in_words(@post.created_at) %> Ago 6

控制器

class PostsController < ApplicationController
    def index
    end
    def addItem
    end
    def create
      @post = Post.new(post_params)
      @post.save
      redirect_to @post
    end
    private
        def post_params
            params.require(:post).permit(:item, :description)
        end
    def show
        @post = Post.find(params[:id])
    end
end

Show.html.erb 查看

<h1 class="item">
    <%= @post.item %>
</h1>
<h1 class="date">
    Submitted:<%= time_ago_in_words(@post.created_at) %> Ago
</h1>
<h1 class="description">
    <%= @post.description %>
</h1>
<h1 class="date">
    Submitted:<%= time_ago_in_words(@post.created_at) %> Ago
</h1>

路线

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  resources :posts
  root "posts#index"
  resources :posts
  root "posts#addItem"
end

将您的 show 方法移到 private

上方

检查您的模型中是否有 "item" 字段 (table)

在Ruby中,您在private关键字下添加的所有方法都将成为私有方法。

在您的情况下,show 方法是私有的,因此 @post 变量在视图中不可用。

将您的 posts_controller 代码更改为此

class PostsController < ApplicationController

    def index
    end

    def create
      @post = Post.new(post_params)
      @post.save
      redirect_to @post
    end

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

    def addItem
    end

    private
      def post_params
        params.require(:post).permit(:item, :description)
      end
end