ruby on rails - How does new method know the errors in the create method? -
a sample code taken http://guides.rubyonrails.org/getting_started.html
controller
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 |f| %> <% if @article.errors.any? %> <div id="error_explanation"> <h2> <%= pluralize(@article.errors.count, "error") %> prohibited article being saved: </h2> <ul> <% @article.errors.full_messages.each |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 %> a statement link
the reason why added
@article = article.newin articlescontroller otherwise@articlenil in our view, , calling@article.errors.any?throw error.
my doubt: if there error while filling form, how @article in new know errors caused @article instance of create action? aren't both different variables? , when render 'new' shouldn't @artcle of create method goes out of scope holds error description , @article of new contain no error information?
when there error in @article creation, there no redirection rendering means render/display new action view i.e new.html.erb without going new action or more precisely without making call new action. see http://brettu.com/rails-daily-ruby-tip-28-whats-the-difference-between-redirect_to-and-render-in-rails/
on errors when render new.html.erb use @article object has errors these lines
@article = article.new(article_params) @article.save #save runs validations so after submit form, purpose of new action done. whole thing handled create action in on errors display errors , uses @article object initialized , saved in create action , on successful creation make call show action using redirect
hope makes sense.
Comments
Post a Comment