我想了解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/
任何幫助將非常感激。我看不到我錯過了什麼。謝謝
我已經迴應有關'@ article'。 '@ testing'似乎沒問題 - 你能粘貼確切的錯誤和你的路由嗎? – Anand 2014-11-25 00:59:19