文章中没有方法错误#显示但实例变量匹配?nil:NilClass 的未定义方法 'title'



articles_controller.rb:

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

show.html.erb:

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

schema.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

routes.rb:

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

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

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

如果id不在路径中,则控制器不知道params的值。即CCD_ 5将是CCD_。这使得@article = nil。因此@article.title在您的视图中导致了此错误。请检查这是否是可能发生的错误。

相关内容

最新更新