首页 > 解决方案 > Articles#show 中的 NoMethodError 但实例变量匹配?nil:NilClass 的未定义方法“标题”

问题描述

文章控制器.rb:

class ArticlesController < ApplicationController

    def show
        @article = Article.find(params[:id])
    end

end

显示.html.erb:

<h1>Showing article details</h1>

<p><strong>Title: </strong><%= @article.title %></p>
<p><strong>Description: </strong><%= @article.description %></p>

架构.rb:

ActiveRecord::Schema.define(version: 2020_04_08_043002) do

  create_table "articles", force: :cascade do |t|
    t.string "title"
    t.text "description"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

路线.rb:

Rails.application.routes.draw do
  root 'pages#home'
  get 'about', to: 'pages#about'
  resources :articles, only: [:show]
end

Ruby 新手,所以我不确定我做错了什么,非常感谢任何帮助!

标签: ruby-on-rails

解决方案


我没有看到代码有任何问题。当你创建一个类似的路由时,resources :articles, only: [:show]它会生成一个 GET 方法,比如/articles/:id. 因此,当您调用 show 操作时,请确保您具有id包含在路径中的值,localhost:3000/articles/779例如。

如果路径中不存在 id,则控制器不知道 params 的值。即params[:id]nil。这使得@article = nil. 因此@article.title在您看来会导致此错误。请检查这是否是可能发生的错误。


推荐阅读