rails route如何知道模型错误

时间:2016-05-18 20:06:22

标签: ruby-on-rails ruby

我跟随this tutorial在轨道上学习ruby,他们在控制器中执行了以下操作:

def new
  @article = Article.new
end

def create
  @article = Article.new(article_params)

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

如果你看到我有箭头的行,那么逻辑是,如果在保存新文章时出错,我应该render 'new'(它会点击new路线?)并呈现再次提供表格,以便我可以在修复错误后重新提交。

我的问题是,新路线如何知道错误是什么?当@article.save失败时,后台是否发生了错误发送的事情?

我很困惑,因为新路线创建了一个新的Article对象并将其发送到视图,如何保留错误?

这里是新的&#39;视图:

<h1>
    file thing add
</h1>
<%= link_to 'Back', articles_path %>

<%= 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 %>

2 个答案:

答案 0 :(得分:3)

当调用ActiveRecord的save方法时,它会尝试使用您的数据存储区进行保存。成功保存将返回更新的模型/对象本身(真实)。不成功的保存尝试将返回false并向您的对象添加errors属性。

基本上你在说

if the article saves successfully
  redirect to the article's SHOW action (in rails router talk)
else
  redirect to the article NEW action

在任何一种情况下,你的@article实例变量都会保留,但在一种情况下,它会向你发送一个步骤,其中有一个方便的errors数组可供使用。

答案 1 :(得分:2)

  

...如果在保存新文章时出错,我应该渲染“新”,点击新路径,然后再次呈现表单,以便我可以在修复错误后重新提交。

     

...我很困惑,因为新路线创建了一个新的Article对象并将其发送到视图,如何保留错误?

这是您做出错误假设的地方。 render 'new'不会将用户重定向到your_controller/new URI。它只是呈现new.html.erb视图。这就是new页面将在您的控制器中拥有当前实例变量的原因。