NoMethodError未定义的方法`'为nil:NilClass

时间:2014-10-12 15:48:03

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

我是使用rails的新手,并且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 命令带来:

{{1}}

知道可能导致此问题的原因吗? 我应该在哪里寻找?

2 个答案:

答案 0 :(得分:3)

您的show操作是私有的,因此无法在视图中使用实例变量@post。将其移至公共范围,问题应该得到解决。

答案 1 :(得分:1)

  1. 将您的节目动作移至公共区块。

  2. nil的未定义方法`***':当您尝试访问实际上尚未创建的对象属性时,实际显示NilClass。

  3. 请务必查看以下视图:

    @atrile.title if @article.title.present?