rails 4.1.14.2 → 5.2.4.4
Sign up to get free protection for your applications and to get access to all the features.
Potentially problematic release.
This version of rails might be problematic. Click here for more details.
- checksums.yaml +5 -5
- data/README.md +33 -19
- metadata +65 -313
- data/guides/CHANGELOG.md +0 -106
- data/guides/Rakefile +0 -77
- data/guides/assets/images/akshaysurve.jpg +0 -0
- data/guides/assets/images/belongs_to.png +0 -0
- data/guides/assets/images/book_icon.gif +0 -0
- data/guides/assets/images/bullet.gif +0 -0
- data/guides/assets/images/chapters_icon.gif +0 -0
- data/guides/assets/images/check_bullet.gif +0 -0
- data/guides/assets/images/credits_pic_blank.gif +0 -0
- data/guides/assets/images/csrf.png +0 -0
- data/guides/assets/images/edge_badge.png +0 -0
- data/guides/assets/images/favicon.ico +0 -0
- data/guides/assets/images/feature_tile.gif +0 -0
- data/guides/assets/images/footer_tile.gif +0 -0
- data/guides/assets/images/fxn.png +0 -0
- data/guides/assets/images/getting_started/article_with_comments.png +0 -0
- data/guides/assets/images/getting_started/challenge.png +0 -0
- data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
- data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
- data/guides/assets/images/getting_started/form_with_errors.png +0 -0
- data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
- data/guides/assets/images/getting_started/new_article.png +0 -0
- data/guides/assets/images/getting_started/rails_welcome.png +0 -0
- data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
- data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
- data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
- data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
- data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
- data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
- data/guides/assets/images/grey_bullet.gif +0 -0
- data/guides/assets/images/habtm.png +0 -0
- data/guides/assets/images/has_many.png +0 -0
- data/guides/assets/images/has_many_through.png +0 -0
- data/guides/assets/images/has_one.png +0 -0
- data/guides/assets/images/has_one_through.png +0 -0
- data/guides/assets/images/header_backdrop.png +0 -0
- data/guides/assets/images/header_tile.gif +0 -0
- data/guides/assets/images/i18n/demo_html_safe.png +0 -0
- data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
- data/guides/assets/images/i18n/demo_translated_en.png +0 -0
- data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
- data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
- data/guides/assets/images/i18n/demo_untranslated.png +0 -0
- data/guides/assets/images/icons/README +0 -5
- data/guides/assets/images/icons/callouts/1.png +0 -0
- data/guides/assets/images/icons/callouts/10.png +0 -0
- data/guides/assets/images/icons/callouts/11.png +0 -0
- data/guides/assets/images/icons/callouts/12.png +0 -0
- data/guides/assets/images/icons/callouts/13.png +0 -0
- data/guides/assets/images/icons/callouts/14.png +0 -0
- data/guides/assets/images/icons/callouts/15.png +0 -0
- data/guides/assets/images/icons/callouts/2.png +0 -0
- data/guides/assets/images/icons/callouts/3.png +0 -0
- data/guides/assets/images/icons/callouts/4.png +0 -0
- data/guides/assets/images/icons/callouts/5.png +0 -0
- data/guides/assets/images/icons/callouts/6.png +0 -0
- data/guides/assets/images/icons/callouts/7.png +0 -0
- data/guides/assets/images/icons/callouts/8.png +0 -0
- data/guides/assets/images/icons/callouts/9.png +0 -0
- data/guides/assets/images/icons/caution.png +0 -0
- data/guides/assets/images/icons/example.png +0 -0
- data/guides/assets/images/icons/home.png +0 -0
- data/guides/assets/images/icons/important.png +0 -0
- data/guides/assets/images/icons/next.png +0 -0
- data/guides/assets/images/icons/note.png +0 -0
- data/guides/assets/images/icons/prev.png +0 -0
- data/guides/assets/images/icons/tip.png +0 -0
- data/guides/assets/images/icons/up.png +0 -0
- data/guides/assets/images/icons/warning.png +0 -0
- data/guides/assets/images/nav_arrow.gif +0 -0
- data/guides/assets/images/oscardelben.jpg +0 -0
- data/guides/assets/images/polymorphic.png +0 -0
- data/guides/assets/images/radar.png +0 -0
- data/guides/assets/images/rails4_features.png +0 -0
- data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
- data/guides/assets/images/rails_guides_logo.gif +0 -0
- data/guides/assets/images/rails_logo_remix.gif +0 -0
- data/guides/assets/images/session_fixation.png +0 -0
- data/guides/assets/images/tab_grey.gif +0 -0
- data/guides/assets/images/tab_info.gif +0 -0
- data/guides/assets/images/tab_note.gif +0 -0
- data/guides/assets/images/tab_red.gif +0 -0
- data/guides/assets/images/tab_yellow.gif +0 -0
- data/guides/assets/images/tab_yellow.png +0 -0
- data/guides/assets/images/vijaydev.jpg +0 -0
- data/guides/assets/javascripts/guides.js +0 -53
- data/guides/assets/javascripts/jquery.min.js +0 -4
- data/guides/assets/javascripts/responsive-tables.js +0 -43
- data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
- data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
- data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
- data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
- data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
- data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
- data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
- data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
- data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
- data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
- data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
- data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
- data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
- data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
- data/guides/assets/javascripts/syntaxhighlighter/shCore.js +0 -17
- data/guides/assets/stylesheets/fixes.css +0 -16
- data/guides/assets/stylesheets/kindle.css +0 -11
- data/guides/assets/stylesheets/main.css +0 -710
- data/guides/assets/stylesheets/print.css +0 -52
- data/guides/assets/stylesheets/reset.css +0 -43
- data/guides/assets/stylesheets/responsive-tables.css +0 -50
- data/guides/assets/stylesheets/style.css +0 -13
- data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +0 -226
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
- data/guides/bug_report_templates/action_controller_gem.rb +0 -47
- data/guides/bug_report_templates/action_controller_master.rb +0 -53
- data/guides/bug_report_templates/active_record_gem.rb +0 -40
- data/guides/bug_report_templates/active_record_master.rb +0 -49
- data/guides/bug_report_templates/generic_gem.rb +0 -15
- data/guides/bug_report_templates/generic_master.rb +0 -26
- data/guides/code/getting_started/Gemfile +0 -40
- data/guides/code/getting_started/Gemfile.lock +0 -125
- data/guides/code/getting_started/README.rdoc +0 -28
- data/guides/code/getting_started/Rakefile +0 -6
- data/guides/code/getting_started/app/assets/javascripts/application.js +0 -15
- data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +0 -3
- data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +0 -3
- data/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee +0 -3
- data/guides/code/getting_started/app/assets/stylesheets/application.css +0 -13
- data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +0 -3
- data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +0 -3
- data/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss +0 -3
- data/guides/code/getting_started/app/controllers/application_controller.rb +0 -5
- data/guides/code/getting_started/app/controllers/comments_controller.rb +0 -23
- data/guides/code/getting_started/app/controllers/posts_controller.rb +0 -53
- data/guides/code/getting_started/app/controllers/welcome_controller.rb +0 -4
- data/guides/code/getting_started/app/helpers/application_helper.rb +0 -2
- data/guides/code/getting_started/app/helpers/comments_helper.rb +0 -2
- data/guides/code/getting_started/app/helpers/posts_helper.rb +0 -2
- data/guides/code/getting_started/app/helpers/welcome_helper.rb +0 -2
- data/guides/code/getting_started/app/models/comment.rb +0 -3
- data/guides/code/getting_started/app/models/post.rb +0 -7
- data/guides/code/getting_started/app/views/comments/_comment.html.erb +0 -15
- data/guides/code/getting_started/app/views/comments/_form.html.erb +0 -13
- data/guides/code/getting_started/app/views/layouts/application.html.erb +0 -14
- data/guides/code/getting_started/app/views/posts/_form.html.erb +0 -27
- data/guides/code/getting_started/app/views/posts/edit.html.erb +0 -5
- data/guides/code/getting_started/app/views/posts/index.html.erb +0 -21
- data/guides/code/getting_started/app/views/posts/new.html.erb +0 -5
- data/guides/code/getting_started/app/views/posts/show.html.erb +0 -18
- data/guides/code/getting_started/app/views/welcome/index.html.erb +0 -4
- data/guides/code/getting_started/bin/bundle +0 -4
- data/guides/code/getting_started/bin/rails +0 -4
- data/guides/code/getting_started/bin/rake +0 -4
- data/guides/code/getting_started/config.ru +0 -4
- data/guides/code/getting_started/config/application.rb +0 -18
- data/guides/code/getting_started/config/boot.rb +0 -4
- data/guides/code/getting_started/config/database.yml +0 -25
- data/guides/code/getting_started/config/environment.rb +0 -5
- data/guides/code/getting_started/config/environments/development.rb +0 -30
- data/guides/code/getting_started/config/environments/production.rb +0 -80
- data/guides/code/getting_started/config/environments/test.rb +0 -36
- data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +0 -7
- data/guides/code/getting_started/config/initializers/filter_parameter_logging.rb +0 -4
- data/guides/code/getting_started/config/initializers/inflections.rb +0 -16
- data/guides/code/getting_started/config/initializers/locale.rb +0 -9
- data/guides/code/getting_started/config/initializers/mime_types.rb +0 -5
- data/guides/code/getting_started/config/initializers/secret_token.rb +0 -12
- data/guides/code/getting_started/config/initializers/session_store.rb +0 -3
- data/guides/code/getting_started/config/initializers/wrap_parameters.rb +0 -14
- data/guides/code/getting_started/config/locales/en.yml +0 -23
- data/guides/code/getting_started/config/routes.rb +0 -7
- data/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb +0 -10
- data/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb +0 -11
- data/guides/code/getting_started/db/schema.rb +0 -33
- data/guides/code/getting_started/db/seeds.rb +0 -7
- data/guides/code/getting_started/public/404.html +0 -60
- data/guides/code/getting_started/public/422.html +0 -60
- data/guides/code/getting_started/public/500.html +0 -59
- data/guides/code/getting_started/public/favicon.ico +0 -0
- data/guides/code/getting_started/public/robots.txt +0 -5
- data/guides/code/getting_started/test/controllers/comments_controller_test.rb +0 -7
- data/guides/code/getting_started/test/controllers/posts_controller_test.rb +0 -7
- data/guides/code/getting_started/test/controllers/welcome_controller_test.rb +0 -9
- data/guides/code/getting_started/test/fixtures/comments.yml +0 -11
- data/guides/code/getting_started/test/fixtures/posts.yml +0 -9
- data/guides/code/getting_started/test/helpers/comments_helper_test.rb +0 -4
- data/guides/code/getting_started/test/helpers/posts_helper_test.rb +0 -4
- data/guides/code/getting_started/test/helpers/welcome_helper_test.rb +0 -4
- data/guides/code/getting_started/test/models/comment_test.rb +0 -7
- data/guides/code/getting_started/test/models/post_test.rb +0 -7
- data/guides/code/getting_started/test/test_helper.rb +0 -12
- data/guides/rails_guides.rb +0 -63
- data/guides/rails_guides/generator.rb +0 -248
- data/guides/rails_guides/helpers.rb +0 -53
- data/guides/rails_guides/indexer.rb +0 -68
- data/guides/rails_guides/kindle.rb +0 -119
- data/guides/rails_guides/levenshtein.rb +0 -31
- data/guides/rails_guides/markdown.rb +0 -163
- data/guides/rails_guides/markdown/renderer.rb +0 -82
- data/guides/source/2_2_release_notes.md +0 -435
- data/guides/source/2_3_release_notes.md +0 -621
- data/guides/source/3_0_release_notes.md +0 -611
- data/guides/source/3_1_release_notes.md +0 -556
- data/guides/source/3_2_release_notes.md +0 -565
- data/guides/source/4_0_release_notes.md +0 -276
- data/guides/source/4_1_release_notes.md +0 -731
- data/guides/source/_license.html.erb +0 -2
- data/guides/source/_welcome.html.erb +0 -25
- data/guides/source/action_controller_overview.md +0 -1175
- data/guides/source/action_mailer_basics.md +0 -689
- data/guides/source/action_view_overview.md +0 -1602
- data/guides/source/active_model_basics.md +0 -200
- data/guides/source/active_record_basics.md +0 -373
- data/guides/source/active_record_callbacks.md +0 -410
- data/guides/source/active_record_querying.md +0 -1785
- data/guides/source/active_record_validations.md +0 -1169
- data/guides/source/active_support_core_extensions.md +0 -3817
- data/guides/source/active_support_instrumentation.md +0 -496
- data/guides/source/api_documentation_guidelines.md +0 -315
- data/guides/source/asset_pipeline.md +0 -1165
- data/guides/source/association_basics.md +0 -2229
- data/guides/source/caching_with_rails.md +0 -354
- data/guides/source/command_line.md +0 -603
- data/guides/source/configuring.md +0 -942
- data/guides/source/contributing_to_ruby_on_rails.md +0 -544
- data/guides/source/credits.html.erb +0 -80
- data/guides/source/debugging_rails_applications.md +0 -707
- data/guides/source/development_dependencies_install.md +0 -278
- data/guides/source/documents.yaml +0 -193
- data/guides/source/engines.md +0 -1412
- data/guides/source/form_helpers.md +0 -1001
- data/guides/source/generators.md +0 -663
- data/guides/source/getting_started.md +0 -1946
- data/guides/source/i18n.md +0 -1043
- data/guides/source/index.html.erb +0 -27
- data/guides/source/initialization.md +0 -657
- data/guides/source/kindle/copyright.html.erb +0 -1
- data/guides/source/kindle/layout.html.erb +0 -27
- data/guides/source/kindle/rails_guides.opf.erb +0 -52
- data/guides/source/kindle/toc.html.erb +0 -24
- data/guides/source/kindle/toc.ncx.erb +0 -64
- data/guides/source/kindle/welcome.html.erb +0 -5
- data/guides/source/layout.html.erb +0 -146
- data/guides/source/layouts_and_rendering.md +0 -1226
- data/guides/source/maintenance_policy.md +0 -75
- data/guides/source/migrations.md +0 -1143
- data/guides/source/nested_model_forms.md +0 -225
- data/guides/source/plugins.md +0 -444
- data/guides/source/rails_application_templates.md +0 -248
- data/guides/source/rails_on_rack.md +0 -332
- data/guides/source/routing.md +0 -1115
- data/guides/source/ruby_on_rails_guides_guidelines.md +0 -128
- data/guides/source/security.md +0 -1018
- data/guides/source/testing.md +0 -1052
- data/guides/source/upgrading_ruby_on_rails.md +0 -928
- data/guides/source/working_with_javascript_in_rails.md +0 -405
- data/guides/w3c_validator.rb +0 -95
@@ -1,1169 +0,0 @@
|
|
1
|
-
Active Record Validations
|
2
|
-
=========================
|
3
|
-
|
4
|
-
This guide teaches you how to validate the state of objects before they go into
|
5
|
-
the database using Active Record's validations feature.
|
6
|
-
|
7
|
-
After reading this guide, you will know:
|
8
|
-
|
9
|
-
* How to use the built-in Active Record validation helpers.
|
10
|
-
* How to create your own custom validation methods.
|
11
|
-
* How to work with the error messages generated by the validation process.
|
12
|
-
|
13
|
-
--------------------------------------------------------------------------------
|
14
|
-
|
15
|
-
Validations Overview
|
16
|
-
--------------------
|
17
|
-
|
18
|
-
Here's an example of a very simple validation:
|
19
|
-
|
20
|
-
```ruby
|
21
|
-
class Person < ActiveRecord::Base
|
22
|
-
validates :name, presence: true
|
23
|
-
end
|
24
|
-
|
25
|
-
Person.create(name: "John Doe").valid? # => true
|
26
|
-
Person.create(name: nil).valid? # => false
|
27
|
-
```
|
28
|
-
|
29
|
-
As you can see, our validation lets us know that our `Person` is not valid
|
30
|
-
without a `name` attribute. The second `Person` will not be persisted to the
|
31
|
-
database.
|
32
|
-
|
33
|
-
Before we dig into more details, let's talk about how validations fit into the
|
34
|
-
big picture of your application.
|
35
|
-
|
36
|
-
### Why Use Validations?
|
37
|
-
|
38
|
-
Validations are used to ensure that only valid data is saved into your
|
39
|
-
database. For example, it may be important to your application to ensure that
|
40
|
-
every user provides a valid email address and mailing address. Model-level
|
41
|
-
validations are the best way to ensure that only valid data is saved into your
|
42
|
-
database. They are database agnostic, cannot be bypassed by end users, and are
|
43
|
-
convenient to test and maintain. Rails makes them easy to use, provides
|
44
|
-
built-in helpers for common needs, and allows you to create your own validation
|
45
|
-
methods as well.
|
46
|
-
|
47
|
-
There are several other ways to validate data before it is saved into your
|
48
|
-
database, including native database constraints, client-side validations,
|
49
|
-
controller-level validations. Here's a summary of the pros and cons:
|
50
|
-
|
51
|
-
* Database constraints and/or stored procedures make the validation mechanisms
|
52
|
-
database-dependent and can make testing and maintenance more difficult.
|
53
|
-
However, if your database is used by other applications, it may be a good
|
54
|
-
idea to use some constraints at the database level. Additionally,
|
55
|
-
database-level validations can safely handle some things (such as uniqueness
|
56
|
-
in heavily-used tables) that can be difficult to implement otherwise.
|
57
|
-
* Client-side validations can be useful, but are generally unreliable if used
|
58
|
-
alone. If they are implemented using JavaScript, they may be bypassed if
|
59
|
-
JavaScript is turned off in the user's browser. However, if combined with
|
60
|
-
other techniques, client-side validation can be a convenient way to provide
|
61
|
-
users with immediate feedback as they use your site.
|
62
|
-
* Controller-level validations can be tempting to use, but often become
|
63
|
-
unwieldy and difficult to test and maintain. Whenever possible, it's a good
|
64
|
-
idea to keep your controllers skinny, as it will make your application a
|
65
|
-
pleasure to work with in the long run.
|
66
|
-
|
67
|
-
Choose these in certain, specific cases. It's the opinion of the Rails team
|
68
|
-
that model-level validations are the most appropriate in most circumstances.
|
69
|
-
|
70
|
-
### When Does Validation Happen?
|
71
|
-
|
72
|
-
There are two kinds of Active Record objects: those that correspond to a row
|
73
|
-
inside your database and those that do not. When you create a fresh object, for
|
74
|
-
example using the `new` method, that object does not belong to the database
|
75
|
-
yet. Once you call `save` upon that object it will be saved into the
|
76
|
-
appropriate database table. Active Record uses the `new_record?` instance
|
77
|
-
method to determine whether an object is already in the database or not.
|
78
|
-
Consider the following simple Active Record class:
|
79
|
-
|
80
|
-
```ruby
|
81
|
-
class Person < ActiveRecord::Base
|
82
|
-
end
|
83
|
-
```
|
84
|
-
|
85
|
-
We can see how it works by looking at some `rails console` output:
|
86
|
-
|
87
|
-
```ruby
|
88
|
-
$ bin/rails console
|
89
|
-
>> p = Person.new(name: "John Doe")
|
90
|
-
=> #<Person id: nil, name: "John Doe", created_at: nil, updated_at: nil>
|
91
|
-
>> p.new_record?
|
92
|
-
=> true
|
93
|
-
>> p.save
|
94
|
-
=> true
|
95
|
-
>> p.new_record?
|
96
|
-
=> false
|
97
|
-
```
|
98
|
-
|
99
|
-
Creating and saving a new record will send an SQL `INSERT` operation to the
|
100
|
-
database. Updating an existing record will send an SQL `UPDATE` operation
|
101
|
-
instead. Validations are typically run before these commands are sent to the
|
102
|
-
database. If any validations fail, the object will be marked as invalid and
|
103
|
-
Active Record will not perform the `INSERT` or `UPDATE` operation. This avoids
|
104
|
-
storing an invalid object in the database. You can choose to have specific
|
105
|
-
validations run when an object is created, saved, or updated.
|
106
|
-
|
107
|
-
CAUTION: There are many ways to change the state of an object in the database.
|
108
|
-
Some methods will trigger validations, but some will not. This means that it's
|
109
|
-
possible to save an object in the database in an invalid state if you aren't
|
110
|
-
careful.
|
111
|
-
|
112
|
-
The following methods trigger validations, and will save the object to the
|
113
|
-
database only if the object is valid:
|
114
|
-
|
115
|
-
* `create`
|
116
|
-
* `create!`
|
117
|
-
* `save`
|
118
|
-
* `save!`
|
119
|
-
* `update`
|
120
|
-
* `update!`
|
121
|
-
|
122
|
-
The bang versions (e.g. `save!`) raise an exception if the record is invalid.
|
123
|
-
The non-bang versions don't, `save` and `update` return `false`,
|
124
|
-
`create` just returns the object.
|
125
|
-
|
126
|
-
### Skipping Validations
|
127
|
-
|
128
|
-
The following methods skip validations, and will save the object to the
|
129
|
-
database regardless of its validity. They should be used with caution.
|
130
|
-
|
131
|
-
* `decrement!`
|
132
|
-
* `decrement_counter`
|
133
|
-
* `increment!`
|
134
|
-
* `increment_counter`
|
135
|
-
* `toggle!`
|
136
|
-
* `touch`
|
137
|
-
* `update_all`
|
138
|
-
* `update_attribute`
|
139
|
-
* `update_column`
|
140
|
-
* `update_columns`
|
141
|
-
* `update_counters`
|
142
|
-
|
143
|
-
Note that `save` also has the ability to skip validations if passed `validate:
|
144
|
-
false` as argument. This technique should be used with caution.
|
145
|
-
|
146
|
-
* `save(validate: false)`
|
147
|
-
|
148
|
-
### `valid?` and `invalid?`
|
149
|
-
|
150
|
-
To verify whether or not an object is valid, Rails uses the `valid?` method.
|
151
|
-
You can also use this method on your own. `valid?` triggers your validations
|
152
|
-
and returns true if no errors were found in the object, and false otherwise.
|
153
|
-
As you saw above:
|
154
|
-
|
155
|
-
```ruby
|
156
|
-
class Person < ActiveRecord::Base
|
157
|
-
validates :name, presence: true
|
158
|
-
end
|
159
|
-
|
160
|
-
Person.create(name: "John Doe").valid? # => true
|
161
|
-
Person.create(name: nil).valid? # => false
|
162
|
-
```
|
163
|
-
|
164
|
-
After Active Record has performed validations, any errors found can be accessed
|
165
|
-
through the `errors.messages` instance method, which returns a collection of errors.
|
166
|
-
By definition, an object is valid if this collection is empty after running
|
167
|
-
validations.
|
168
|
-
|
169
|
-
Note that an object instantiated with `new` will not report errors even if it's
|
170
|
-
technically invalid, because validations are not run when using `new`.
|
171
|
-
|
172
|
-
```ruby
|
173
|
-
class Person < ActiveRecord::Base
|
174
|
-
validates :name, presence: true
|
175
|
-
end
|
176
|
-
|
177
|
-
>> p = Person.new
|
178
|
-
# => #<Person id: nil, name: nil>
|
179
|
-
>> p.errors.messages
|
180
|
-
# => {}
|
181
|
-
|
182
|
-
>> p.valid?
|
183
|
-
# => false
|
184
|
-
>> p.errors.messages
|
185
|
-
# => {name:["can't be blank"]}
|
186
|
-
|
187
|
-
>> p = Person.create
|
188
|
-
# => #<Person id: nil, name: nil>
|
189
|
-
>> p.errors.messages
|
190
|
-
# => {name:["can't be blank"]}
|
191
|
-
|
192
|
-
>> p.save
|
193
|
-
# => false
|
194
|
-
|
195
|
-
>> p.save!
|
196
|
-
# => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
|
197
|
-
|
198
|
-
>> Person.create!
|
199
|
-
# => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
|
200
|
-
```
|
201
|
-
|
202
|
-
`invalid?` is simply the inverse of `valid?`. It triggers your validations,
|
203
|
-
returning true if any errors were found in the object, and false otherwise.
|
204
|
-
|
205
|
-
### `errors[]`
|
206
|
-
|
207
|
-
To verify whether or not a particular attribute of an object is valid, you can
|
208
|
-
use `errors[:attribute]`. It returns an array of all the errors for
|
209
|
-
`:attribute`. If there are no errors on the specified attribute, an empty array
|
210
|
-
is returned.
|
211
|
-
|
212
|
-
This method is only useful _after_ validations have been run, because it only
|
213
|
-
inspects the errors collection and does not trigger validations itself. It's
|
214
|
-
different from the `ActiveRecord::Base#invalid?` method explained above because
|
215
|
-
it doesn't verify the validity of the object as a whole. It only checks to see
|
216
|
-
whether there are errors found on an individual attribute of the object.
|
217
|
-
|
218
|
-
```ruby
|
219
|
-
class Person < ActiveRecord::Base
|
220
|
-
validates :name, presence: true
|
221
|
-
end
|
222
|
-
|
223
|
-
>> Person.new.errors[:name].any? # => false
|
224
|
-
>> Person.create.errors[:name].any? # => true
|
225
|
-
```
|
226
|
-
|
227
|
-
We'll cover validation errors in greater depth in the [Working with Validation
|
228
|
-
Errors](#working-with-validation-errors) section. For now, let's turn to the
|
229
|
-
built-in validation helpers that Rails provides by default.
|
230
|
-
|
231
|
-
Validation Helpers
|
232
|
-
------------------
|
233
|
-
|
234
|
-
Active Record offers many pre-defined validation helpers that you can use
|
235
|
-
directly inside your class definitions. These helpers provide common validation
|
236
|
-
rules. Every time a validation fails, an error message is added to the object's
|
237
|
-
`errors` collection, and this message is associated with the attribute being
|
238
|
-
validated.
|
239
|
-
|
240
|
-
Each helper accepts an arbitrary number of attribute names, so with a single
|
241
|
-
line of code you can add the same kind of validation to several attributes.
|
242
|
-
|
243
|
-
All of them accept the `:on` and `:message` options, which define when the
|
244
|
-
validation should be run and what message should be added to the `errors`
|
245
|
-
collection if it fails, respectively. The `:on` option takes one of the values
|
246
|
-
`:create` or `:update`. There is a default error
|
247
|
-
message for each one of the validation helpers. These messages are used when
|
248
|
-
the `:message` option isn't specified. Let's take a look at each one of the
|
249
|
-
available helpers.
|
250
|
-
|
251
|
-
### `acceptance`
|
252
|
-
|
253
|
-
This method validates that a checkbox on the user interface was checked when a
|
254
|
-
form was submitted. This is typically used when the user needs to agree to your
|
255
|
-
application's terms of service, confirm reading some text, or any similar
|
256
|
-
concept. This validation is very specific to web applications and this
|
257
|
-
'acceptance' does not need to be recorded anywhere in your database (if you
|
258
|
-
don't have a field for it, the helper will just create a virtual attribute).
|
259
|
-
|
260
|
-
```ruby
|
261
|
-
class Person < ActiveRecord::Base
|
262
|
-
validates :terms_of_service, acceptance: true
|
263
|
-
end
|
264
|
-
```
|
265
|
-
|
266
|
-
The default error message for this helper is _"must be accepted"_.
|
267
|
-
|
268
|
-
It can receive an `:accept` option, which determines the value that will be
|
269
|
-
considered acceptance. It defaults to "1" and can be easily changed.
|
270
|
-
|
271
|
-
```ruby
|
272
|
-
class Person < ActiveRecord::Base
|
273
|
-
validates :terms_of_service, acceptance: { accept: 'yes' }
|
274
|
-
end
|
275
|
-
```
|
276
|
-
|
277
|
-
### `validates_associated`
|
278
|
-
|
279
|
-
You should use this helper when your model has associations with other models
|
280
|
-
and they also need to be validated. When you try to save your object, `valid?`
|
281
|
-
will be called upon each one of the associated objects.
|
282
|
-
|
283
|
-
```ruby
|
284
|
-
class Library < ActiveRecord::Base
|
285
|
-
has_many :books
|
286
|
-
validates_associated :books
|
287
|
-
end
|
288
|
-
```
|
289
|
-
|
290
|
-
This validation will work with all of the association types.
|
291
|
-
|
292
|
-
CAUTION: Don't use `validates_associated` on both ends of your associations.
|
293
|
-
They would call each other in an infinite loop.
|
294
|
-
|
295
|
-
The default error message for `validates_associated` is _"is invalid"_. Note
|
296
|
-
that each associated object will contain its own `errors` collection; errors do
|
297
|
-
not bubble up to the calling model.
|
298
|
-
|
299
|
-
### `confirmation`
|
300
|
-
|
301
|
-
You should use this helper when you have two text fields that should receive
|
302
|
-
exactly the same content. For example, you may want to confirm an email address
|
303
|
-
or a password. This validation creates a virtual attribute whose name is the
|
304
|
-
name of the field that has to be confirmed with "_confirmation" appended.
|
305
|
-
|
306
|
-
```ruby
|
307
|
-
class Person < ActiveRecord::Base
|
308
|
-
validates :email, confirmation: true
|
309
|
-
end
|
310
|
-
```
|
311
|
-
|
312
|
-
In your view template you could use something like
|
313
|
-
|
314
|
-
```erb
|
315
|
-
<%= text_field :person, :email %>
|
316
|
-
<%= text_field :person, :email_confirmation %>
|
317
|
-
```
|
318
|
-
|
319
|
-
This check is performed only if `email_confirmation` is not `nil`. To require
|
320
|
-
confirmation, make sure to add a presence check for the confirmation attribute
|
321
|
-
(we'll take a look at `presence` later on this guide):
|
322
|
-
|
323
|
-
```ruby
|
324
|
-
class Person < ActiveRecord::Base
|
325
|
-
validates :email, confirmation: true
|
326
|
-
validates :email_confirmation, presence: true
|
327
|
-
end
|
328
|
-
```
|
329
|
-
|
330
|
-
The default error message for this helper is _"doesn't match confirmation"_.
|
331
|
-
|
332
|
-
### `exclusion`
|
333
|
-
|
334
|
-
This helper validates that the attributes' values are not included in a given
|
335
|
-
set. In fact, this set can be any enumerable object.
|
336
|
-
|
337
|
-
```ruby
|
338
|
-
class Account < ActiveRecord::Base
|
339
|
-
validates :subdomain, exclusion: { in: %w(www us ca jp),
|
340
|
-
message: "%{value} is reserved." }
|
341
|
-
end
|
342
|
-
```
|
343
|
-
|
344
|
-
The `exclusion` helper has an option `:in` that receives the set of values that
|
345
|
-
will not be accepted for the validated attributes. The `:in` option has an
|
346
|
-
alias called `:within` that you can use for the same purpose, if you'd like to.
|
347
|
-
This example uses the `:message` option to show how you can include the
|
348
|
-
attribute's value.
|
349
|
-
|
350
|
-
The default error message is _"is reserved"_.
|
351
|
-
|
352
|
-
### `format`
|
353
|
-
|
354
|
-
This helper validates the attributes' values by testing whether they match a
|
355
|
-
given regular expression, which is specified using the `:with` option.
|
356
|
-
|
357
|
-
```ruby
|
358
|
-
class Product < ActiveRecord::Base
|
359
|
-
validates :legacy_code, format: { with: /\A[a-zA-Z]+\z/,
|
360
|
-
message: "only allows letters" }
|
361
|
-
end
|
362
|
-
```
|
363
|
-
|
364
|
-
The default error message is _"is invalid"_.
|
365
|
-
|
366
|
-
### `inclusion`
|
367
|
-
|
368
|
-
This helper validates that the attributes' values are included in a given set.
|
369
|
-
In fact, this set can be any enumerable object.
|
370
|
-
|
371
|
-
```ruby
|
372
|
-
class Coffee < ActiveRecord::Base
|
373
|
-
validates :size, inclusion: { in: %w(small medium large),
|
374
|
-
message: "%{value} is not a valid size" }
|
375
|
-
end
|
376
|
-
```
|
377
|
-
|
378
|
-
The `inclusion` helper has an option `:in` that receives the set of values that
|
379
|
-
will be accepted. The `:in` option has an alias called `:within` that you can
|
380
|
-
use for the same purpose, if you'd like to. The previous example uses the
|
381
|
-
`:message` option to show how you can include the attribute's value.
|
382
|
-
|
383
|
-
The default error message for this helper is _"is not included in the list"_.
|
384
|
-
|
385
|
-
### `length`
|
386
|
-
|
387
|
-
This helper validates the length of the attributes' values. It provides a
|
388
|
-
variety of options, so you can specify length constraints in different ways:
|
389
|
-
|
390
|
-
```ruby
|
391
|
-
class Person < ActiveRecord::Base
|
392
|
-
validates :name, length: { minimum: 2 }
|
393
|
-
validates :bio, length: { maximum: 500 }
|
394
|
-
validates :password, length: { in: 6..20 }
|
395
|
-
validates :registration_number, length: { is: 6 }
|
396
|
-
end
|
397
|
-
```
|
398
|
-
|
399
|
-
The possible length constraint options are:
|
400
|
-
|
401
|
-
* `:minimum` - The attribute cannot have less than the specified length.
|
402
|
-
* `:maximum` - The attribute cannot have more than the specified length.
|
403
|
-
* `:in` (or `:within`) - The attribute length must be included in a given
|
404
|
-
interval. The value for this option must be a range.
|
405
|
-
* `:is` - The attribute length must be equal to the given value.
|
406
|
-
|
407
|
-
The default error messages depend on the type of length validation being
|
408
|
-
performed. You can personalize these messages using the `:wrong_length`,
|
409
|
-
`:too_long`, and `:too_short` options and `%{count}` as a placeholder for the
|
410
|
-
number corresponding to the length constraint being used. You can still use the
|
411
|
-
`:message` option to specify an error message.
|
412
|
-
|
413
|
-
```ruby
|
414
|
-
class Person < ActiveRecord::Base
|
415
|
-
validates :bio, length: { maximum: 1000,
|
416
|
-
too_long: "%{count} characters is the maximum allowed" }
|
417
|
-
end
|
418
|
-
```
|
419
|
-
|
420
|
-
This helper counts characters by default, but you can split the value in a
|
421
|
-
different way using the `:tokenizer` option:
|
422
|
-
|
423
|
-
```ruby
|
424
|
-
class Essay < ActiveRecord::Base
|
425
|
-
validates :content, length: {
|
426
|
-
minimum: 300,
|
427
|
-
maximum: 400,
|
428
|
-
tokenizer: lambda { |str| str.scan(/\w+/) },
|
429
|
-
too_short: "must have at least %{count} words",
|
430
|
-
too_long: "must have at most %{count} words"
|
431
|
-
}
|
432
|
-
end
|
433
|
-
```
|
434
|
-
|
435
|
-
Note that the default error messages are plural (e.g., "is too short (minimum
|
436
|
-
is %{count} characters)"). For this reason, when `:minimum` is 1 you should
|
437
|
-
provide a personalized message or use `presence: true` instead. When
|
438
|
-
`:in` or `:within` have a lower limit of 1, you should either provide a
|
439
|
-
personalized message or call `presence` prior to `length`.
|
440
|
-
|
441
|
-
### `numericality`
|
442
|
-
|
443
|
-
This helper validates that your attributes have only numeric values. By
|
444
|
-
default, it will match an optional sign followed by an integral or floating
|
445
|
-
point number. To specify that only integral numbers are allowed set
|
446
|
-
`:only_integer` to true.
|
447
|
-
|
448
|
-
If you set `:only_integer` to `true`, then it will use the
|
449
|
-
|
450
|
-
```ruby
|
451
|
-
/\A[+-]?\d+\Z/
|
452
|
-
```
|
453
|
-
|
454
|
-
regular expression to validate the attribute's value. Otherwise, it will try to
|
455
|
-
convert the value to a number using `Float`.
|
456
|
-
|
457
|
-
WARNING. Note that the regular expression above allows a trailing newline
|
458
|
-
character.
|
459
|
-
|
460
|
-
```ruby
|
461
|
-
class Player < ActiveRecord::Base
|
462
|
-
validates :points, numericality: true
|
463
|
-
validates :games_played, numericality: { only_integer: true }
|
464
|
-
end
|
465
|
-
```
|
466
|
-
|
467
|
-
Besides `:only_integer`, this helper also accepts the following options to add
|
468
|
-
constraints to acceptable values:
|
469
|
-
|
470
|
-
* `:greater_than` - Specifies the value must be greater than the supplied
|
471
|
-
value. The default error message for this option is _"must be greater than
|
472
|
-
%{count}"_.
|
473
|
-
* `:greater_than_or_equal_to` - Specifies the value must be greater than or
|
474
|
-
equal to the supplied value. The default error message for this option is
|
475
|
-
_"must be greater than or equal to %{count}"_.
|
476
|
-
* `:equal_to` - Specifies the value must be equal to the supplied value. The
|
477
|
-
default error message for this option is _"must be equal to %{count}"_.
|
478
|
-
* `:less_than` - Specifies the value must be less than the supplied value. The
|
479
|
-
default error message for this option is _"must be less than %{count}"_.
|
480
|
-
* `:less_than_or_equal_to` - Specifies the value must be less than or equal the
|
481
|
-
supplied value. The default error message for this option is _"must be less
|
482
|
-
than or equal to %{count}"_.
|
483
|
-
* `:odd` - Specifies the value must be an odd number if set to true. The
|
484
|
-
default error message for this option is _"must be odd"_.
|
485
|
-
* `:even` - Specifies the value must be an even number if set to true. The
|
486
|
-
default error message for this option is _"must be even"_.
|
487
|
-
|
488
|
-
The default error message is _"is not a number"_.
|
489
|
-
|
490
|
-
### `presence`
|
491
|
-
|
492
|
-
This helper validates that the specified attributes are not empty. It uses the
|
493
|
-
`blank?` method to check if the value is either `nil` or a blank string, that
|
494
|
-
is, a string that is either empty or consists of whitespace.
|
495
|
-
|
496
|
-
```ruby
|
497
|
-
class Person < ActiveRecord::Base
|
498
|
-
validates :name, :login, :email, presence: true
|
499
|
-
end
|
500
|
-
```
|
501
|
-
|
502
|
-
If you want to be sure that an association is present, you'll need to test
|
503
|
-
whether the associated object itself is present, and not the foreign key used
|
504
|
-
to map the association.
|
505
|
-
|
506
|
-
```ruby
|
507
|
-
class LineItem < ActiveRecord::Base
|
508
|
-
belongs_to :order
|
509
|
-
validates :order, presence: true
|
510
|
-
end
|
511
|
-
```
|
512
|
-
|
513
|
-
In order to validate associated records whose presence is required, you must
|
514
|
-
specify the `:inverse_of` option for the association:
|
515
|
-
|
516
|
-
```ruby
|
517
|
-
class Order < ActiveRecord::Base
|
518
|
-
has_many :line_items, inverse_of: :order
|
519
|
-
end
|
520
|
-
```
|
521
|
-
|
522
|
-
If you validate the presence of an object associated via a `has_one` or
|
523
|
-
`has_many` relationship, it will check that the object is neither `blank?` nor
|
524
|
-
`marked_for_destruction?`.
|
525
|
-
|
526
|
-
Since `false.blank?` is true, if you want to validate the presence of a boolean
|
527
|
-
field you should use `validates :field_name, inclusion: { in: [true, false] }`.
|
528
|
-
|
529
|
-
The default error message is _"can't be blank"_.
|
530
|
-
|
531
|
-
### `absence`
|
532
|
-
|
533
|
-
This helper validates that the specified attributes are absent. It uses the
|
534
|
-
`present?` method to check if the value is not either nil or a blank string, that
|
535
|
-
is, a string that is either empty or consists of whitespace.
|
536
|
-
|
537
|
-
```ruby
|
538
|
-
class Person < ActiveRecord::Base
|
539
|
-
validates :name, :login, :email, absence: true
|
540
|
-
end
|
541
|
-
```
|
542
|
-
|
543
|
-
If you want to be sure that an association is absent, you'll need to test
|
544
|
-
whether the associated object itself is absent, and not the foreign key used
|
545
|
-
to map the association.
|
546
|
-
|
547
|
-
```ruby
|
548
|
-
class LineItem < ActiveRecord::Base
|
549
|
-
belongs_to :order
|
550
|
-
validates :order, absence: true
|
551
|
-
end
|
552
|
-
```
|
553
|
-
|
554
|
-
In order to validate associated records whose absence is required, you must
|
555
|
-
specify the `:inverse_of` option for the association:
|
556
|
-
|
557
|
-
```ruby
|
558
|
-
class Order < ActiveRecord::Base
|
559
|
-
has_many :line_items, inverse_of: :order
|
560
|
-
end
|
561
|
-
```
|
562
|
-
|
563
|
-
If you validate the absence of an object associated via a `has_one` or
|
564
|
-
`has_many` relationship, it will check that the object is neither `present?` nor
|
565
|
-
`marked_for_destruction?`.
|
566
|
-
|
567
|
-
Since `false.present?` is false, if you want to validate the absence of a boolean
|
568
|
-
field you should use `validates :field_name, exclusion: { in: [true, false] }`.
|
569
|
-
|
570
|
-
The default error message is _"must be blank"_.
|
571
|
-
|
572
|
-
### `uniqueness`
|
573
|
-
|
574
|
-
This helper validates that the attribute's value is unique right before the
|
575
|
-
object gets saved. It does not create a uniqueness constraint in the database,
|
576
|
-
so it may happen that two different database connections create two records
|
577
|
-
with the same value for a column that you intend to be unique. To avoid that,
|
578
|
-
you must create a unique index on both columns in your database. See
|
579
|
-
[the MySQL manual](http://dev.mysql.com/doc/refman/5.6/en/multiple-column-indexes.html)
|
580
|
-
for more details about multiple column indexes.
|
581
|
-
|
582
|
-
```ruby
|
583
|
-
class Account < ActiveRecord::Base
|
584
|
-
validates :email, uniqueness: true
|
585
|
-
end
|
586
|
-
```
|
587
|
-
|
588
|
-
The validation happens by performing an SQL query into the model's table,
|
589
|
-
searching for an existing record with the same value in that attribute.
|
590
|
-
|
591
|
-
There is a `:scope` option that you can use to specify other attributes that
|
592
|
-
are used to limit the uniqueness check:
|
593
|
-
|
594
|
-
```ruby
|
595
|
-
class Holiday < ActiveRecord::Base
|
596
|
-
validates :name, uniqueness: { scope: :year,
|
597
|
-
message: "should happen once per year" }
|
598
|
-
end
|
599
|
-
```
|
600
|
-
|
601
|
-
There is also a `:case_sensitive` option that you can use to define whether the
|
602
|
-
uniqueness constraint will be case sensitive or not. This option defaults to
|
603
|
-
true.
|
604
|
-
|
605
|
-
```ruby
|
606
|
-
class Person < ActiveRecord::Base
|
607
|
-
validates :name, uniqueness: { case_sensitive: false }
|
608
|
-
end
|
609
|
-
```
|
610
|
-
|
611
|
-
WARNING. Note that some databases are configured to perform case-insensitive
|
612
|
-
searches anyway.
|
613
|
-
|
614
|
-
The default error message is _"has already been taken"_.
|
615
|
-
|
616
|
-
### `validates_with`
|
617
|
-
|
618
|
-
This helper passes the record to a separate class for validation.
|
619
|
-
|
620
|
-
```ruby
|
621
|
-
class GoodnessValidator < ActiveModel::Validator
|
622
|
-
def validate(record)
|
623
|
-
if record.first_name == "Evil"
|
624
|
-
record.errors[:base] << "This person is evil"
|
625
|
-
end
|
626
|
-
end
|
627
|
-
end
|
628
|
-
|
629
|
-
class Person < ActiveRecord::Base
|
630
|
-
validates_with GoodnessValidator
|
631
|
-
end
|
632
|
-
```
|
633
|
-
|
634
|
-
NOTE: Errors added to `record.errors[:base]` relate to the state of the record
|
635
|
-
as a whole, and not to a specific attribute.
|
636
|
-
|
637
|
-
The `validates_with` helper takes a class, or a list of classes to use for
|
638
|
-
validation. There is no default error message for `validates_with`. You must
|
639
|
-
manually add errors to the record's errors collection in the validator class.
|
640
|
-
|
641
|
-
To implement the validate method, you must have a `record` parameter defined,
|
642
|
-
which is the record to be validated.
|
643
|
-
|
644
|
-
Like all other validations, `validates_with` takes the `:if`, `:unless` and
|
645
|
-
`:on` options. If you pass any other options, it will send those options to the
|
646
|
-
validator class as `options`:
|
647
|
-
|
648
|
-
```ruby
|
649
|
-
class GoodnessValidator < ActiveModel::Validator
|
650
|
-
def validate(record)
|
651
|
-
if options[:fields].any?{|field| record.send(field) == "Evil" }
|
652
|
-
record.errors[:base] << "This person is evil"
|
653
|
-
end
|
654
|
-
end
|
655
|
-
end
|
656
|
-
|
657
|
-
class Person < ActiveRecord::Base
|
658
|
-
validates_with GoodnessValidator, fields: [:first_name, :last_name]
|
659
|
-
end
|
660
|
-
```
|
661
|
-
|
662
|
-
Note that the validator will be initialized *only once* for the whole application
|
663
|
-
life cycle, and not on each validation run, so be careful about using instance
|
664
|
-
variables inside it.
|
665
|
-
|
666
|
-
If your validator is complex enough that you want instance variables, you can
|
667
|
-
easily use a plain old Ruby object instead:
|
668
|
-
|
669
|
-
```ruby
|
670
|
-
class Person < ActiveRecord::Base
|
671
|
-
validate do |person|
|
672
|
-
GoodnessValidator.new(person).validate
|
673
|
-
end
|
674
|
-
end
|
675
|
-
|
676
|
-
class GoodnessValidator
|
677
|
-
def initialize(person)
|
678
|
-
@person = person
|
679
|
-
end
|
680
|
-
|
681
|
-
def validate
|
682
|
-
if some_complex_condition_involving_ivars_and_private_methods?
|
683
|
-
@person.errors[:base] << "This person is evil"
|
684
|
-
end
|
685
|
-
end
|
686
|
-
|
687
|
-
# ...
|
688
|
-
end
|
689
|
-
```
|
690
|
-
|
691
|
-
### `validates_each`
|
692
|
-
|
693
|
-
This helper validates attributes against a block. It doesn't have a predefined
|
694
|
-
validation function. You should create one using a block, and every attribute
|
695
|
-
passed to `validates_each` will be tested against it. In the following example,
|
696
|
-
we don't want names and surnames to begin with lower case.
|
697
|
-
|
698
|
-
```ruby
|
699
|
-
class Person < ActiveRecord::Base
|
700
|
-
validates_each :name, :surname do |record, attr, value|
|
701
|
-
record.errors.add(attr, 'must start with upper case') if value =~ /\A[a-z]/
|
702
|
-
end
|
703
|
-
end
|
704
|
-
```
|
705
|
-
|
706
|
-
The block receives the record, the attribute's name and the attribute's value.
|
707
|
-
You can do anything you like to check for valid data within the block. If your
|
708
|
-
validation fails, you should add an error message to the model, therefore
|
709
|
-
making it invalid.
|
710
|
-
|
711
|
-
Common Validation Options
|
712
|
-
-------------------------
|
713
|
-
|
714
|
-
These are common validation options:
|
715
|
-
|
716
|
-
### `:allow_nil`
|
717
|
-
|
718
|
-
The `:allow_nil` option skips the validation when the value being validated is
|
719
|
-
`nil`.
|
720
|
-
|
721
|
-
```ruby
|
722
|
-
class Coffee < ActiveRecord::Base
|
723
|
-
validates :size, inclusion: { in: %w(small medium large),
|
724
|
-
message: "%{value} is not a valid size" }, allow_nil: true
|
725
|
-
end
|
726
|
-
```
|
727
|
-
|
728
|
-
### `:allow_blank`
|
729
|
-
|
730
|
-
The `:allow_blank` option is similar to the `:allow_nil` option. This option
|
731
|
-
will let validation pass if the attribute's value is `blank?`, like `nil` or an
|
732
|
-
empty string for example.
|
733
|
-
|
734
|
-
```ruby
|
735
|
-
class Topic < ActiveRecord::Base
|
736
|
-
validates :title, length: { is: 5 }, allow_blank: true
|
737
|
-
end
|
738
|
-
|
739
|
-
Topic.create(title: "").valid? # => true
|
740
|
-
Topic.create(title: nil).valid? # => true
|
741
|
-
```
|
742
|
-
|
743
|
-
### `:message`
|
744
|
-
|
745
|
-
As you've already seen, the `:message` option lets you specify the message that
|
746
|
-
will be added to the `errors` collection when validation fails. When this
|
747
|
-
option is not used, Active Record will use the respective default error message
|
748
|
-
for each validation helper.
|
749
|
-
|
750
|
-
### `:on`
|
751
|
-
|
752
|
-
The `:on` option lets you specify when the validation should happen. The
|
753
|
-
default behavior for all the built-in validation helpers is to be run on save
|
754
|
-
(both when you're creating a new record and when you're updating it). If you
|
755
|
-
want to change it, you can use `on: :create` to run the validation only when a
|
756
|
-
new record is created or `on: :update` to run the validation only when a record
|
757
|
-
is updated.
|
758
|
-
|
759
|
-
```ruby
|
760
|
-
class Person < ActiveRecord::Base
|
761
|
-
# it will be possible to update email with a duplicated value
|
762
|
-
validates :email, uniqueness: true, on: :create
|
763
|
-
|
764
|
-
# it will be possible to create the record with a non-numerical age
|
765
|
-
validates :age, numericality: true, on: :update
|
766
|
-
|
767
|
-
# the default (validates on both create and update)
|
768
|
-
validates :name, presence: true
|
769
|
-
end
|
770
|
-
```
|
771
|
-
|
772
|
-
Strict Validations
|
773
|
-
------------------
|
774
|
-
|
775
|
-
You can also specify validations to be strict and raise
|
776
|
-
`ActiveModel::StrictValidationFailed` when the object is invalid.
|
777
|
-
|
778
|
-
```ruby
|
779
|
-
class Person < ActiveRecord::Base
|
780
|
-
validates :name, presence: { strict: true }
|
781
|
-
end
|
782
|
-
|
783
|
-
Person.new.valid? # => ActiveModel::StrictValidationFailed: Name can't be blank
|
784
|
-
```
|
785
|
-
|
786
|
-
There is also an ability to pass custom exception to `:strict` option.
|
787
|
-
|
788
|
-
```ruby
|
789
|
-
class Person < ActiveRecord::Base
|
790
|
-
validates :token, presence: true, uniqueness: true, strict: TokenGenerationException
|
791
|
-
end
|
792
|
-
|
793
|
-
Person.new.valid? # => TokenGenerationException: Token can't be blank
|
794
|
-
```
|
795
|
-
|
796
|
-
Conditional Validation
|
797
|
-
----------------------
|
798
|
-
|
799
|
-
Sometimes it will make sense to validate an object only when a given predicate
|
800
|
-
is satisfied. You can do that by using the `:if` and `:unless` options, which
|
801
|
-
can take a symbol, a string, a `Proc` or an `Array`. You may use the `:if`
|
802
|
-
option when you want to specify when the validation **should** happen. If you
|
803
|
-
want to specify when the validation **should not** happen, then you may use the
|
804
|
-
`:unless` option.
|
805
|
-
|
806
|
-
### Using a Symbol with `:if` and `:unless`
|
807
|
-
|
808
|
-
You can associate the `:if` and `:unless` options with a symbol corresponding
|
809
|
-
to the name of a method that will get called right before validation happens.
|
810
|
-
This is the most commonly used option.
|
811
|
-
|
812
|
-
```ruby
|
813
|
-
class Order < ActiveRecord::Base
|
814
|
-
validates :card_number, presence: true, if: :paid_with_card?
|
815
|
-
|
816
|
-
def paid_with_card?
|
817
|
-
payment_type == "card"
|
818
|
-
end
|
819
|
-
end
|
820
|
-
```
|
821
|
-
|
822
|
-
### Using a String with `:if` and `:unless`
|
823
|
-
|
824
|
-
You can also use a string that will be evaluated using `eval` and needs to
|
825
|
-
contain valid Ruby code. You should use this option only when the string
|
826
|
-
represents a really short condition.
|
827
|
-
|
828
|
-
```ruby
|
829
|
-
class Person < ActiveRecord::Base
|
830
|
-
validates :surname, presence: true, if: "name.nil?"
|
831
|
-
end
|
832
|
-
```
|
833
|
-
|
834
|
-
### Using a Proc with `:if` and `:unless`
|
835
|
-
|
836
|
-
Finally, it's possible to associate `:if` and `:unless` with a `Proc` object
|
837
|
-
which will be called. Using a `Proc` object gives you the ability to write an
|
838
|
-
inline condition instead of a separate method. This option is best suited for
|
839
|
-
one-liners.
|
840
|
-
|
841
|
-
```ruby
|
842
|
-
class Account < ActiveRecord::Base
|
843
|
-
validates :password, confirmation: true,
|
844
|
-
unless: Proc.new { |a| a.password.blank? }
|
845
|
-
end
|
846
|
-
```
|
847
|
-
|
848
|
-
### Grouping Conditional validations
|
849
|
-
|
850
|
-
Sometimes it is useful to have multiple validations use one condition, it can
|
851
|
-
be easily achieved using `with_options`.
|
852
|
-
|
853
|
-
```ruby
|
854
|
-
class User < ActiveRecord::Base
|
855
|
-
with_options if: :is_admin? do |admin|
|
856
|
-
admin.validates :password, length: { minimum: 10 }
|
857
|
-
admin.validates :email, presence: true
|
858
|
-
end
|
859
|
-
end
|
860
|
-
```
|
861
|
-
|
862
|
-
All validations inside of `with_options` block will have automatically passed
|
863
|
-
the condition `if: :is_admin?`
|
864
|
-
|
865
|
-
### Combining Validation Conditions
|
866
|
-
|
867
|
-
On the other hand, when multiple conditions define whether or not a validation
|
868
|
-
should happen, an `Array` can be used. Moreover, you can apply both `:if` and
|
869
|
-
`:unless` to the same validation.
|
870
|
-
|
871
|
-
```ruby
|
872
|
-
class Computer < ActiveRecord::Base
|
873
|
-
validates :mouse, presence: true,
|
874
|
-
if: ["market.retail?", :desktop?],
|
875
|
-
unless: Proc.new { |c| c.trackpad.present? }
|
876
|
-
end
|
877
|
-
```
|
878
|
-
|
879
|
-
The validation only runs when all the `:if` conditions and none of the
|
880
|
-
`:unless` conditions are evaluated to `true`.
|
881
|
-
|
882
|
-
Performing Custom Validations
|
883
|
-
-----------------------------
|
884
|
-
|
885
|
-
When the built-in validation helpers are not enough for your needs, you can
|
886
|
-
write your own validators or validation methods as you prefer.
|
887
|
-
|
888
|
-
### Custom Validators
|
889
|
-
|
890
|
-
Custom validators are classes that extend `ActiveModel::Validator`. These
|
891
|
-
classes must implement a `validate` method which takes a record as an argument
|
892
|
-
and performs the validation on it. The custom validator is called using the
|
893
|
-
`validates_with` method.
|
894
|
-
|
895
|
-
```ruby
|
896
|
-
class MyValidator < ActiveModel::Validator
|
897
|
-
def validate(record)
|
898
|
-
unless record.name.starts_with? 'X'
|
899
|
-
record.errors[:name] << 'Need a name starting with X please!'
|
900
|
-
end
|
901
|
-
end
|
902
|
-
end
|
903
|
-
|
904
|
-
class Person
|
905
|
-
include ActiveModel::Validations
|
906
|
-
validates_with MyValidator
|
907
|
-
end
|
908
|
-
```
|
909
|
-
|
910
|
-
The easiest way to add custom validators for validating individual attributes
|
911
|
-
is with the convenient `ActiveModel::EachValidator`. In this case, the custom
|
912
|
-
validator class must implement a `validate_each` method which takes three
|
913
|
-
arguments: record, attribute and value which correspond to the instance, the
|
914
|
-
attribute to be validated and the value of the attribute in the passed
|
915
|
-
instance.
|
916
|
-
|
917
|
-
```ruby
|
918
|
-
class EmailValidator < ActiveModel::EachValidator
|
919
|
-
def validate_each(record, attribute, value)
|
920
|
-
unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
|
921
|
-
record.errors[attribute] << (options[:message] || "is not an email")
|
922
|
-
end
|
923
|
-
end
|
924
|
-
end
|
925
|
-
|
926
|
-
class Person < ActiveRecord::Base
|
927
|
-
validates :email, presence: true, email: true
|
928
|
-
end
|
929
|
-
```
|
930
|
-
|
931
|
-
As shown in the example, you can also combine standard validations with your
|
932
|
-
own custom validators.
|
933
|
-
|
934
|
-
### Custom Methods
|
935
|
-
|
936
|
-
You can also create methods that verify the state of your models and add
|
937
|
-
messages to the `errors` collection when they are invalid. You must then
|
938
|
-
register these methods by using the `validate` class method, passing in the
|
939
|
-
symbols for the validation methods' names.
|
940
|
-
|
941
|
-
You can pass more than one symbol for each class method and the respective
|
942
|
-
validations will be run in the same order as they were registered.
|
943
|
-
|
944
|
-
```ruby
|
945
|
-
class Invoice < ActiveRecord::Base
|
946
|
-
validate :expiration_date_cannot_be_in_the_past,
|
947
|
-
:discount_cannot_be_greater_than_total_value
|
948
|
-
|
949
|
-
def expiration_date_cannot_be_in_the_past
|
950
|
-
if expiration_date.present? && expiration_date < Date.today
|
951
|
-
errors.add(:expiration_date, "can't be in the past")
|
952
|
-
end
|
953
|
-
end
|
954
|
-
|
955
|
-
def discount_cannot_be_greater_than_total_value
|
956
|
-
if discount > total_value
|
957
|
-
errors.add(:discount, "can't be greater than total value")
|
958
|
-
end
|
959
|
-
end
|
960
|
-
end
|
961
|
-
```
|
962
|
-
|
963
|
-
By default such validations will run every time you call `valid?`. It is also
|
964
|
-
possible to control when to run these custom validations by giving an `:on`
|
965
|
-
option to the `validate` method, with either: `:create` or `:update`.
|
966
|
-
|
967
|
-
```ruby
|
968
|
-
class Invoice < ActiveRecord::Base
|
969
|
-
validate :active_customer, on: :create
|
970
|
-
|
971
|
-
def active_customer
|
972
|
-
errors.add(:customer_id, "is not active") unless customer.active?
|
973
|
-
end
|
974
|
-
end
|
975
|
-
```
|
976
|
-
|
977
|
-
Working with Validation Errors
|
978
|
-
------------------------------
|
979
|
-
|
980
|
-
In addition to the `valid?` and `invalid?` methods covered earlier, Rails provides a number of methods for working with the `errors` collection and inquiring about the validity of objects.
|
981
|
-
|
982
|
-
The following is a list of the most commonly used methods. Please refer to the `ActiveModel::Errors` documentation for a list of all the available methods.
|
983
|
-
|
984
|
-
### `errors`
|
985
|
-
|
986
|
-
Returns an instance of the class `ActiveModel::Errors` containing all errors. Each key is the attribute name and the value is an array of strings with all errors.
|
987
|
-
|
988
|
-
```ruby
|
989
|
-
class Person < ActiveRecord::Base
|
990
|
-
validates :name, presence: true, length: { minimum: 3 }
|
991
|
-
end
|
992
|
-
|
993
|
-
person = Person.new
|
994
|
-
person.valid? # => false
|
995
|
-
person.errors.messages
|
996
|
-
# => {:name=>["can't be blank", "is too short (minimum is 3 characters)"]}
|
997
|
-
|
998
|
-
person = Person.new(name: "John Doe")
|
999
|
-
person.valid? # => true
|
1000
|
-
person.errors.messages # => {}
|
1001
|
-
```
|
1002
|
-
|
1003
|
-
### `errors[]`
|
1004
|
-
|
1005
|
-
`errors[]` is used when you want to check the error messages for a specific attribute. It returns an array of strings with all error messages for the given attribute, each string with one error message. If there are no errors related to the attribute, it returns an empty array.
|
1006
|
-
|
1007
|
-
```ruby
|
1008
|
-
class Person < ActiveRecord::Base
|
1009
|
-
validates :name, presence: true, length: { minimum: 3 }
|
1010
|
-
end
|
1011
|
-
|
1012
|
-
person = Person.new(name: "John Doe")
|
1013
|
-
person.valid? # => true
|
1014
|
-
person.errors[:name] # => []
|
1015
|
-
|
1016
|
-
person = Person.new(name: "JD")
|
1017
|
-
person.valid? # => false
|
1018
|
-
person.errors[:name] # => ["is too short (minimum is 3 characters)"]
|
1019
|
-
|
1020
|
-
person = Person.new
|
1021
|
-
person.valid? # => false
|
1022
|
-
person.errors[:name]
|
1023
|
-
# => ["can't be blank", "is too short (minimum is 3 characters)"]
|
1024
|
-
```
|
1025
|
-
|
1026
|
-
### `errors.add`
|
1027
|
-
|
1028
|
-
The `add` method lets you manually add messages that are related to particular attributes. You can use the `errors.full_messages` or `errors.to_a` methods to view the messages in the form they might be displayed to a user. Those particular messages get the attribute name prepended (and capitalized). `add` receives the name of the attribute you want to add the message to, and the message itself.
|
1029
|
-
|
1030
|
-
```ruby
|
1031
|
-
class Person < ActiveRecord::Base
|
1032
|
-
def a_method_used_for_validation_purposes
|
1033
|
-
errors.add(:name, "cannot contain the characters !@#%*()_-+=")
|
1034
|
-
end
|
1035
|
-
end
|
1036
|
-
|
1037
|
-
person = Person.create(name: "!@#")
|
1038
|
-
|
1039
|
-
person.errors[:name]
|
1040
|
-
# => ["cannot contain the characters !@#%*()_-+="]
|
1041
|
-
|
1042
|
-
person.errors.full_messages
|
1043
|
-
# => ["Name cannot contain the characters !@#%*()_-+="]
|
1044
|
-
```
|
1045
|
-
|
1046
|
-
Another way to do this is using `[]=` setter
|
1047
|
-
|
1048
|
-
```ruby
|
1049
|
-
class Person < ActiveRecord::Base
|
1050
|
-
def a_method_used_for_validation_purposes
|
1051
|
-
errors[:name] = "cannot contain the characters !@#%*()_-+="
|
1052
|
-
end
|
1053
|
-
end
|
1054
|
-
|
1055
|
-
person = Person.create(name: "!@#")
|
1056
|
-
|
1057
|
-
person.errors[:name]
|
1058
|
-
# => ["cannot contain the characters !@#%*()_-+="]
|
1059
|
-
|
1060
|
-
person.errors.to_a
|
1061
|
-
# => ["Name cannot contain the characters !@#%*()_-+="]
|
1062
|
-
```
|
1063
|
-
|
1064
|
-
### `errors[:base]`
|
1065
|
-
|
1066
|
-
You can add error messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. Since `errors[:base]` is an array, you can simply add a string to it and it will be used as an error message.
|
1067
|
-
|
1068
|
-
```ruby
|
1069
|
-
class Person < ActiveRecord::Base
|
1070
|
-
def a_method_used_for_validation_purposes
|
1071
|
-
errors[:base] << "This person is invalid because ..."
|
1072
|
-
end
|
1073
|
-
end
|
1074
|
-
```
|
1075
|
-
|
1076
|
-
### `errors.clear`
|
1077
|
-
|
1078
|
-
The `clear` method is used when you intentionally want to clear all the messages in the `errors` collection. Of course, calling `errors.clear` upon an invalid object won't actually make it valid: the `errors` collection will now be empty, but the next time you call `valid?` or any method that tries to save this object to the database, the validations will run again. If any of the validations fail, the `errors` collection will be filled again.
|
1079
|
-
|
1080
|
-
```ruby
|
1081
|
-
class Person < ActiveRecord::Base
|
1082
|
-
validates :name, presence: true, length: { minimum: 3 }
|
1083
|
-
end
|
1084
|
-
|
1085
|
-
person = Person.new
|
1086
|
-
person.valid? # => false
|
1087
|
-
person.errors[:name]
|
1088
|
-
# => ["can't be blank", "is too short (minimum is 3 characters)"]
|
1089
|
-
|
1090
|
-
person.errors.clear
|
1091
|
-
person.errors.empty? # => true
|
1092
|
-
|
1093
|
-
p.save # => false
|
1094
|
-
|
1095
|
-
p.errors[:name]
|
1096
|
-
# => ["can't be blank", "is too short (minimum is 3 characters)"]
|
1097
|
-
```
|
1098
|
-
|
1099
|
-
### `errors.size`
|
1100
|
-
|
1101
|
-
The `size` method returns the total number of error messages for the object.
|
1102
|
-
|
1103
|
-
```ruby
|
1104
|
-
class Person < ActiveRecord::Base
|
1105
|
-
validates :name, presence: true, length: { minimum: 3 }
|
1106
|
-
end
|
1107
|
-
|
1108
|
-
person = Person.new
|
1109
|
-
person.valid? # => false
|
1110
|
-
person.errors.size # => 2
|
1111
|
-
|
1112
|
-
person = Person.new(name: "Andrea", email: "andrea@example.com")
|
1113
|
-
person.valid? # => true
|
1114
|
-
person.errors.size # => 0
|
1115
|
-
```
|
1116
|
-
|
1117
|
-
Displaying Validation Errors in Views
|
1118
|
-
-------------------------------------
|
1119
|
-
|
1120
|
-
Once you've created a model and added validations, if that model is created via
|
1121
|
-
a web form, you probably want to display an error message when one of the
|
1122
|
-
validations fail.
|
1123
|
-
|
1124
|
-
Because every application handles this kind of thing differently, Rails does
|
1125
|
-
not include any view helpers to help you generate these messages directly.
|
1126
|
-
However, due to the rich number of methods Rails gives you to interact with
|
1127
|
-
validations in general, it's fairly easy to build your own. In addition, when
|
1128
|
-
generating a scaffold, Rails will put some ERB into the `_form.html.erb` that
|
1129
|
-
it generates that displays the full list of errors on that model.
|
1130
|
-
|
1131
|
-
Assuming we have a model that's been saved in an instance variable named
|
1132
|
-
`@post`, it looks like this:
|
1133
|
-
|
1134
|
-
```ruby
|
1135
|
-
<% if @post.errors.any? %>
|
1136
|
-
<div id="error_explanation">
|
1137
|
-
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
|
1138
|
-
|
1139
|
-
<ul>
|
1140
|
-
<% @post.errors.full_messages.each do |msg| %>
|
1141
|
-
<li><%= msg %></li>
|
1142
|
-
<% end %>
|
1143
|
-
</ul>
|
1144
|
-
</div>
|
1145
|
-
<% end %>
|
1146
|
-
```
|
1147
|
-
|
1148
|
-
Furthermore, if you use the Rails form helpers to generate your forms, when
|
1149
|
-
a validation error occurs on a field, it will generate an extra `<div>` around
|
1150
|
-
the entry.
|
1151
|
-
|
1152
|
-
```
|
1153
|
-
<div class="field_with_errors">
|
1154
|
-
<input id="post_title" name="post[title]" size="30" type="text" value="">
|
1155
|
-
</div>
|
1156
|
-
```
|
1157
|
-
|
1158
|
-
You can then style this div however you'd like. The default scaffold that
|
1159
|
-
Rails generates, for example, adds this CSS rule:
|
1160
|
-
|
1161
|
-
```
|
1162
|
-
.field_with_errors {
|
1163
|
-
padding: 2px;
|
1164
|
-
background-color: red;
|
1165
|
-
display: table;
|
1166
|
-
}
|
1167
|
-
```
|
1168
|
-
|
1169
|
-
This means that any field with an error ends up with a 2 pixel red border.
|