2014-11-25 48 views
0

我想了解Ruby on Rails指南後Ruby on Rails的絕對基礎知識。但是,我有一個問題想顯示在控制器初始化的變量,在視圖中:無論是在測試和展示的觀點,它說「未定義的方法爲無:NilClass」視圖中的實例變量

app/controllers/articles_controller

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 test 
    @testing = [0, 1, 2, 3] 
    end 

end 



app/views/articles/new.html.haml 

= form_for :article, :url => articles_path do |f| 
    %p 
    = f.label :title 
    %br/ 
    = f.text_field :title 
    %p 
    = f.label :text 
    %br/ 
    = f.text_field :title 
    %p 
    = f.submit 



app/views/articles/show.html.haml 

%p 
    Title: 
    %br/ 
    = @article.title 
%p 
    Text: 
    %br/ 
    = @article.text 


app/views/articles/test.html.haml 

= @testing[0] 

這是我得到的顯示視圖的錯誤:

NoMethodError in ArticlesController#show 
undefined method `title' for nil:NilClass 

Title: 
%br/ 
= @article.title 
%p 
Text: 
%br/ 

任何幫助將非常感激。我看不到我錯過了什麼。謝謝

+0

我已經迴應有關'@ article'。 '@ testing'似乎沒問題 - 你能粘貼確切的錯誤和你的路由嗎? – Anand 2014-11-25 00:59:19

回答

2

您在控制器中使用@article,在視圖中使用@articles。在視圖中將@articles更改爲@article。

另外,將私有方法移動到類的底部 - show和test方法現在在您的控制器中是私有的。

class ArticlesController < ApplicationController 

    def new 
    end 

    def create 
    @article = Article.new(article_params) 
    @article.save 
    redirect_to @article 
    end 

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

    def test 
    @testing = [0, 1, 2, 3] 
    end 

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

你說得對。但我解決了這個問題,但仍然無法正常工作。 – FranGoitia 2014-11-25 00:58:56

+0

什麼不起作用?你會得到什麼錯誤?粘貼整個錯誤消息。 – Anand 2014-11-25 01:00:14

+0

非常感謝!問題在於這些方法是私有的 – FranGoitia 2014-11-25 01:10:14