@@ -695,9 +695,8 @@ in "Active Record Validations and
695
695
Callbacks":active_record_validations_callbacks.html#validations-overview
696
696
697
697
If you open +posts_controller+ again, you'll notice that we don't check
698
- the result of calling
[email protected] +, but now if we don't pass a valid
699
- title, +save+ will return false and we need to show the form back to the
700
- user. To do that, modify the +create+ action to look like the following:
698
+ the result of calling
[email protected] +. We need to change its behavior to
699
+ show the form back to the user if any error occur:
701
700
702
701
<ruby>
703
702
def new
@@ -716,12 +715,12 @@ end
716
715
</ruby>
717
716
718
717
Notice that I've also added +@post = Post.new+ to the +new+ action. I'll
719
- explain why I did that in the next section.
718
+ explain why I did that in the next section, for now add that to your
719
+ controller as well.
720
720
721
- Now, if validations fail and +save+ returns false, we show the form back
722
- to the user. Note that we use +render+ instead of +redirect_to+. We do
723
- that because +render+ will pass the +@post+ variable back to the form,
724
- which contains the error information that we need.
721
+ Also notice that we use +render+ instead of +redirect_to+ when +save+
722
+ returns false. We can use +render+ so that the +@post+ object is passed
723
+ back to the view.
725
724
726
725
If you reload
727
726
"http://localhost:3000/posts/new":http://localhost:3000/posts/new and
@@ -762,8 +761,10 @@ something went wrong. To do that, you'll modify
762
761
</erb>
763
762
764
763
A few things are going on. We check if there are any errors with
765
- [email protected] ?+, and if that returns true we show the list of all
766
- errors with
[email protected] _messages+. +pluralize+ is a rails helper
764
+ [email protected] ?+, and in that case we show a list of all
765
+ errors with
[email protected] _messages+.
766
+
767
+ +pluralize+ is a rails helper
767
768
that takes a number and a string as its arguments. If the number is
768
769
greater than one, the string will be automatically pluralized.
769
770
@@ -775,7 +776,9 @@ TIP: Rails automatically wraps fields that contain an error with a div
775
776
with class +field_with_errors+. You can define a css rule to make them
776
777
standout.
777
778
779
+ Now you'll get a nice error message when saving a post without title:
778
780
781
+ !images/getting_started/form_with_errors.png(Form With Errors)!
779
782
780
783
h4. Using the Console
781
784
0 commit comments