视图中的实例变量

时间:2014-11-25 00:49:54

标签: ruby-on-rails ruby model-view-controller

我正在尝试按照Ruby on Rails指南学习Ruby on Rails的绝对基础知识。但是,我在尝试在视图中显示在控制器中初始化的变量时遇到问题:在test和show视图中它都显示“nil的未定义方法: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]

这是我在show视图中得到的错误:

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

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

任何帮助都会非常感激。我不明白我错过了什么。感谢

1 个答案:

答案 0 :(得分: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