我是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操作是私有的,因此不能在视图中使用实例变量@post。把它移到一个公共的范围,问题应该得到解决。

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

10-11 07:49