【问题标题】:NoMethodError undefined method ` ' for nil:NilClassNoMethodError 未定义方法 ` ' 用于 nil:NilClass
【发布时间】:2014-10-12 15:48:03
【问题描述】:

我是 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

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • ...“入门”中的这样一个陷阱:)
    【解决方案2】:
    1. 将您的表演动作移至公开屏蔽。

    2. nil:NilClass 的未定义方法“***”实际上是在您尝试访问实际上尚未创建的对象属性时显示的。

    3. 总是像这样检查视图:

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

    【讨论】:

    • 这仍然会失败。 @articlenil 在这种情况下不是 .title。我认为你的意思是@article.title if @article。但是,在这种情况下,我会反对这一点。当你请求一个存在的资源时,那么这个资源不应该是nil
    猜你喜欢
    • 2016-06-15
    • 2013-02-17
    • 2014-03-16
    • 1970-01-01
    • 2013-11-14
    • 2013-01-14
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多