首页 > rails入门时的NoMethodError in Articles#show

rails入门时的NoMethodError in Articles#show

刚刚入门rails,照着rails guide的代码敲,但是数据库,没问题,就是controller没办法传数据到view
代码如下

articles_controller.rb

    class ArticlesController < ApplicationController
      def new
      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

      def index
        @article = Article.all
      end


 end

show.html.erb

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

<p>
  <strong>Text:</strong>
  <%= @article.text %>
</p>


但是却显示问题

NoMethodError in Articles#show

Showing /home/aljun/rubylearning/railstest/app/views/articles/show.html.erb where line #3 raised:

undefined method `title' for nil:NilClass

Extracted source (around line #3):

1
2
3
4
5
6

Title:

check

Rails.root: /home/aljun/rubylearning/railstest
Application Trace | Framework Trace | Full Trace

app/views/articles/show.html.erb:3:in `_app_views_articles_show_html_erb___3692144343305583486_70248134395300'

检查过数据库里面有数据,在rails的错误网页上用命令行写出过Article有数据的


你的show方法定义成了private了


除了已经提到过的private method问题,你的Article model里面确实有title这个属性吗?


在 private 下面的代码都是私有方法,你这样写,报错是正常的。把 show 和 index 移上去就行了

另外,给你(初学者)的建议,写代码尽量按 风格 来。
参考:Ruby 风格指导

【热门文章】
【热门文章】