ruby-on-rails - NoMethodError 未定义方法 ` ' 为 nil :NilClass

标签 ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

我是 Rails 新手,从 http://guides.rubyonrails.org/getting_started.html 开始卡在 5.7 Showing Articles 并出现以下错误:

NoMethodError in Articles#show
Showing /home/jakub/workspace/blog/blog/app/views/articles/show.erb where line #3 raised:

undefined method `title' for nil:NilClass

来源在哪里:

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

  <p>

articles_controller.rb是:

class ArticlesController < ApplicationController

  def index
    @articles = Article.all
  end

  def create
    @article = Article.new(article_params)

    @article.save
    redirect_to @article
  end

  private
  def article_params
    params.require(:article).permit(:title, :text)
  end

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

end

rake routes命令带来:

        Prefix Verb   URI Pattern                  Controller#Action
welcome_contact GET    /welcome/contact(.:format)   welcome#contact
  welcome_index GET    /welcome/index(.:format)     welcome#index
       articles GET    /articles(.:format)          articles#index
                POST   /articles(.:format)          articles#create
    new_article GET    /articles/new(.:format)      articles#new
   edit_article GET    /articles/:id/edit(.:format) articles#edit
        article GET    /articles/:id(.:format)      articles#show
                PATCH  /articles/:id(.:format)      articles#update
                PUT    /articles/:id(.:format)      articles#update
                DELETE /articles/:id(.:format)      articles#destroy
           root GET    /                            welcome#index

知道是什么导致了这个问题吗? 我应该在哪里寻找?

最佳答案

您的show 操作是私有(private)的,因此不能在 View 中使用实例变量@post。将其移至公共(public)范围,问题应该得到解决。

关于ruby-on-rails - NoMethodError 未定义方法 ` ' 为 nil :NilClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26326941/

相关文章:

ruby-on-rails - 在保存到 Rails 之前将输入转换为整数

ruby-on-rails - 有没有一种方法可以在 list 文件中将异常添加到require_tree?

ruby - 从字符串中删除所有非大写字母单词正则表达式rails

ruby-on-rails - 使用 bundle install 安装 bcrypt 时出错

javascript - 如何在 Rails 中自动获取元描述和关键字?

ruby-on-rails-3 - 如何从 Rails 3 中的模型获取实际的 HTTP 请求?

Ruby on Rails 教程中的 SQL 插值

ruby-on-rails - 如何获取 Controller 可用的操作列表?

ruby-on-rails - Ruby:如何解析字符串 '3 days ago'?

javascript - 用于 Rails 后端的基于主干的 Web 应用程序 : separate project or on top of rails?