2015-08-30 42 views
0

http://guides.rubyonrails.org/getting_started.html新方法如何知道创建方法中的错误?

控制器

def new 
    @article = Article.new 
end 

def create 
    @article = Article.new(article_params) 

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

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

new.html.erb

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

    <% if @article.errors.any? %> 
    <div id="error_explanation"> 
     <h2> 
     <%= pluralize(@article.errors.count, "error") %> prohibited 
     this article from being saved: 
     </h2> 
     <ul> 
     <% @article.errors.full_messages.each do |msg| %> 
      <li><%= msg %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% 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 %> 

从这个链接的声明取出的样本代码

为什么我们加入@article = Article.new原因文章控件r是否则@article将在我们的 视图中为零,并且调用@article.errors.any?会引发错误。

我的疑问: 如果有错误,而填写表格,如何在new@article了解造成的create行动@article实例的错误?他们不是两个不同的变数吗?当我们render 'new'不应该的create方法超出范围,其中包含的错误说明和@articlenew不包含错误信息?

+0

如下所述,'render'中的'new'是模板new.html.erb,而不是新的动作。 –

回答

1

当存在@article创造任何错误,也没有重定向,但渲染,这意味着它只会render/display新动作视图即new.html.erb而不去新的动作或者更准确地说,而不拨打另一个电话,以新的动作。看到这个http://brettu.com/rails-daily-ruby-tip-28-whats-the-difference-between-redirect_to-and-render-in-rails/

在错误的时候会呈现new.html.erb它将使用@article对象,它拥有所有你从这些线路

@article = Article.new(article_params) 
@article.save #save basically runs the validations 

让您提交表单所以基本上之后的错误,新行动的目的已经完成。现在,整个事情将创造一种对错误就会显示错误,并使用你初始化并保存在创建行动,并在成功创建它将拨打另一个电话使用显示操作重定向

希望它@article对象操作处理说得通。

+1

ty,现在很清楚:) – InQusitive