ruby-on-rails - 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 新手,所以我不确定我做错了什么,非常感谢任何帮助!
解决方案
我没有看到代码有任何问题。当你创建一个类似的路由时,resources :articles, only: [:show]
它会生成一个 GET 方法,比如/articles/:id
. 因此,当您调用 show 操作时,请确保您具有id
包含在路径中的值,localhost:3000/articles/779
例如。
如果路径中不存在 id,则控制器不知道 params 的值。即params[:id]
会nil
。这使得@article = nil
. 因此@article.title
在您看来会导致此错误。请检查这是否是可能发生的错误。
推荐阅读
- php - 如何从 MYSQL 数据库分配的 PHP 会话数组中打印单个变量
- java - 如果文件与最后使用的文件同名,Java 程序不会读取文件内容
- string - 获取没有字符的字符串的所有子字符串的时间复杂度是多少?
- microsoft-graph-api - 如何使用图形 API 获取 O365 共享点文件夹上的文件内容
- javascript - 如何为 vanilla 浏览器 javascript 开发打包多个 ES6 类?
- google-apps-script - 我在脚本属性中存储了一个对象,但它以字符串的形式返回
- php - 致命错误:未捕获的 ImagickException:PDFDelegateFailed
- symfony - 使用 Encore 导入 SCSS 文件的路径是什么?
- python-3.x - 有没有办法找到9结束后的数字总和?
- javascript - 将 % 的文本放在第 1 行,其余的放在第 2 行