Abdul Ahmad Abdul Ahmad - 1 year ago 53
Ruby Question

how does rails route know model errors

I'm following this tutorial to learn ruby on rails and they did the following in the controller:

def new
@article = Article.new

def create
@article = Article.new(article_params)

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

if you see the line where I have the arrow, the logic is, if there is an error in saving a new article, I should
render 'new'
(which hits the
route?) and renders the form again so I can resubmit after fixing errors.

my question is, how does the new route know what the errors were? Is there something happening in the background that sends over the error when

I'm confused because the new route creates a new Article object and sends it to the view, how are errors preserved?

here's the 'new' view:

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

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

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

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

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

<%= f.submit %>
<% end %>


When ActiveRecord's save method is called, it attempts a save with your datastore. a successful save will return the updated model/object itself (truthy). an unsuccessful save attempt will return false AND add an errors property to your object.

Essentially you are saying

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

in either case your @article instance variable will persist, but in one case it is sending you back a step with a handy errors array to work with.