2015-12-18 74 views
0

我正在学习Ruby on Rails,并开始我通过http://guides.rubyonrails.org/getting_started.html#showing-articles来制作这个小博客应用程序。 现在我在5.10,我需要这样当用户添加了一个丝毫不差,长度以验证添加到表单短于5Ruby on Rails指南(博客)错误5.10

所以这是我articles_controller.rb:

class ArticlesController < ApplicationController 
    def index 
     @articles = Article.all 
    end 

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

    def new 
    end 

    def create 
     #render plain: params[:article].inspect 

     #@article = Article.new(params[:article]) 

     @article = Article.new(article_params) 

     #@article.save 
     if @article.save 
      redirect_to @article 
     else 
      render 'new' 
     end 

     redirect_to @article 
    end 

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

而且在这种观点我有一个错误(new.html.erb):

<%= form_for :article, url: articles_path do |f| %> 

    <% if @article.errors.any? %> 
    <% end %> 

    <p> 
    <%= f.label :title %><br> 
    <%= f.text_field :title %> 
    </p> 

    <p> 
    <%= f.label :text %><br> 
    <%= f.text_area :text %> 
    </p> 

    <p> 
    <%= f.submit %> 
    </p> 

<% end %> 

<%= link_to 'Back', articles_path %> 

这是错误我得到:

enter image description here

我是Ruby和rails的新手,所以我希望能得到一些帮助。

+1

Marek Lipka给了你正确的答案。其他几件事情 - 在Ruby(和Rails)中,它被认为是使用缩进的一种很好的风格,由2个空格组成(而不是4个)。另外,在你的创建动作中不需要第二个'redirect_to @ article'。 –

+0

是的,它现在可以工作,谢谢Marek Lipka。但是,我可以解释为什么我需要这条线或它做了什么? –

+0

为什么它会使用由2个空格组成的缩进? –

回答

2

您没有初始化@article实例变量,但您尝试tu在new视图中使用它。你应该有:

def new 
    @article = Article.new 
end