activerecord 2.3.18 → 3.2.22
Sign up to get free protection for your applications and to get access to all the features.
Potentially problematic release.
This version of activerecord might be problematic. Click here for more details.
- checksums.yaml +7 -0
- data/CHANGELOG.md +1014 -0
- data/MIT-LICENSE +20 -0
- data/README.rdoc +222 -0
- data/examples/performance.rb +100 -126
- data/examples/simple.rb +14 -0
- data/lib/active_record/aggregations.rb +93 -99
- data/lib/active_record/associations/alias_tracker.rb +76 -0
- data/lib/active_record/associations/association.rb +247 -0
- data/lib/active_record/associations/association_scope.rb +134 -0
- data/lib/active_record/associations/belongs_to_association.rb +54 -61
- data/lib/active_record/associations/belongs_to_polymorphic_association.rb +17 -59
- data/lib/active_record/associations/builder/association.rb +55 -0
- data/lib/active_record/associations/builder/belongs_to.rb +88 -0
- data/lib/active_record/associations/builder/collection_association.rb +75 -0
- data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +57 -0
- data/lib/active_record/associations/builder/has_many.rb +71 -0
- data/lib/active_record/associations/builder/has_one.rb +62 -0
- data/lib/active_record/associations/builder/singular_association.rb +32 -0
- data/lib/active_record/associations/collection_association.rb +580 -0
- data/lib/active_record/associations/collection_proxy.rb +133 -0
- data/lib/active_record/associations/has_and_belongs_to_many_association.rb +39 -119
- data/lib/active_record/associations/has_many_association.rb +60 -79
- data/lib/active_record/associations/has_many_through_association.rb +127 -206
- data/lib/active_record/associations/has_one_association.rb +55 -114
- data/lib/active_record/associations/has_one_through_association.rb +25 -26
- data/lib/active_record/associations/join_dependency/join_association.rb +159 -0
- data/lib/active_record/associations/join_dependency/join_base.rb +24 -0
- data/lib/active_record/associations/join_dependency/join_part.rb +78 -0
- data/lib/active_record/associations/join_dependency.rb +214 -0
- data/lib/active_record/associations/join_helper.rb +55 -0
- data/lib/active_record/associations/preloader/association.rb +125 -0
- data/lib/active_record/associations/preloader/belongs_to.rb +17 -0
- data/lib/active_record/associations/preloader/collection_association.rb +24 -0
- data/lib/active_record/associations/preloader/has_and_belongs_to_many.rb +60 -0
- data/lib/active_record/associations/preloader/has_many.rb +17 -0
- data/lib/active_record/associations/preloader/has_many_through.rb +15 -0
- data/lib/active_record/associations/preloader/has_one.rb +23 -0
- data/lib/active_record/associations/preloader/has_one_through.rb +9 -0
- data/lib/active_record/associations/preloader/singular_association.rb +21 -0
- data/lib/active_record/associations/preloader/through_association.rb +67 -0
- data/lib/active_record/associations/preloader.rb +181 -0
- data/lib/active_record/associations/singular_association.rb +64 -0
- data/lib/active_record/associations/through_association.rb +87 -0
- data/lib/active_record/associations.rb +693 -1337
- data/lib/active_record/attribute_assignment.rb +221 -0
- data/lib/active_record/attribute_methods/before_type_cast.rb +31 -0
- data/lib/active_record/attribute_methods/deprecated_underscore_read.rb +32 -0
- data/lib/active_record/attribute_methods/dirty.rb +111 -0
- data/lib/active_record/attribute_methods/primary_key.rb +114 -0
- data/lib/active_record/attribute_methods/query.rb +39 -0
- data/lib/active_record/attribute_methods/read.rb +136 -0
- data/lib/active_record/attribute_methods/serialization.rb +120 -0
- data/lib/active_record/attribute_methods/time_zone_conversion.rb +65 -0
- data/lib/active_record/attribute_methods/write.rb +70 -0
- data/lib/active_record/attribute_methods.rb +211 -339
- data/lib/active_record/autosave_association.rb +179 -149
- data/lib/active_record/base.rb +401 -2907
- data/lib/active_record/callbacks.rb +91 -176
- data/lib/active_record/coders/yaml_column.rb +41 -0
- data/lib/active_record/connection_adapters/abstract/connection_pool.rb +236 -119
- data/lib/active_record/connection_adapters/abstract/connection_specification.rb +110 -58
- data/lib/active_record/connection_adapters/abstract/database_limits.rb +12 -11
- data/lib/active_record/connection_adapters/abstract/database_statements.rb +175 -74
- data/lib/active_record/connection_adapters/abstract/query_cache.rb +31 -35
- data/lib/active_record/connection_adapters/abstract/quoting.rb +71 -21
- data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +81 -311
- data/lib/active_record/connection_adapters/abstract/schema_statements.rb +194 -78
- data/lib/active_record/connection_adapters/abstract_adapter.rb +130 -83
- data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +676 -0
- data/lib/active_record/connection_adapters/column.rb +296 -0
- data/lib/active_record/connection_adapters/mysql2_adapter.rb +280 -0
- data/lib/active_record/connection_adapters/mysql_adapter.rb +272 -493
- data/lib/active_record/connection_adapters/postgresql_adapter.rb +650 -405
- data/lib/active_record/connection_adapters/schema_cache.rb +69 -0
- data/lib/active_record/connection_adapters/sqlite3_adapter.rb +30 -9
- data/lib/active_record/connection_adapters/sqlite_adapter.rb +276 -147
- data/lib/active_record/connection_adapters/statement_pool.rb +40 -0
- data/lib/active_record/counter_cache.rb +123 -0
- data/lib/active_record/dynamic_finder_match.rb +41 -14
- data/lib/active_record/dynamic_matchers.rb +84 -0
- data/lib/active_record/dynamic_scope_match.rb +13 -15
- data/lib/active_record/errors.rb +195 -0
- data/lib/active_record/explain.rb +86 -0
- data/lib/active_record/explain_subscriber.rb +25 -0
- data/lib/active_record/fixtures/file.rb +65 -0
- data/lib/active_record/fixtures.rb +695 -770
- data/lib/active_record/identity_map.rb +162 -0
- data/lib/active_record/inheritance.rb +174 -0
- data/lib/active_record/integration.rb +60 -0
- data/lib/active_record/locale/en.yml +9 -27
- data/lib/active_record/locking/optimistic.rb +76 -73
- data/lib/active_record/locking/pessimistic.rb +32 -10
- data/lib/active_record/log_subscriber.rb +72 -0
- data/lib/active_record/migration/command_recorder.rb +105 -0
- data/lib/active_record/migration.rb +415 -205
- data/lib/active_record/model_schema.rb +368 -0
- data/lib/active_record/nested_attributes.rb +153 -63
- data/lib/active_record/observer.rb +27 -103
- data/lib/active_record/persistence.rb +376 -0
- data/lib/active_record/query_cache.rb +49 -8
- data/lib/active_record/querying.rb +58 -0
- data/lib/active_record/railtie.rb +131 -0
- data/lib/active_record/railties/console_sandbox.rb +6 -0
- data/lib/active_record/railties/controller_runtime.rb +49 -0
- data/lib/active_record/railties/databases.rake +659 -0
- data/lib/active_record/railties/jdbcmysql_error.rb +16 -0
- data/lib/active_record/readonly_attributes.rb +26 -0
- data/lib/active_record/reflection.rb +269 -120
- data/lib/active_record/relation/batches.rb +90 -0
- data/lib/active_record/relation/calculations.rb +372 -0
- data/lib/active_record/relation/delegation.rb +49 -0
- data/lib/active_record/relation/finder_methods.rb +402 -0
- data/lib/active_record/relation/predicate_builder.rb +63 -0
- data/lib/active_record/relation/query_methods.rb +417 -0
- data/lib/active_record/relation/spawn_methods.rb +180 -0
- data/lib/active_record/relation.rb +537 -0
- data/lib/active_record/result.rb +40 -0
- data/lib/active_record/sanitization.rb +194 -0
- data/lib/active_record/schema.rb +9 -6
- data/lib/active_record/schema_dumper.rb +55 -32
- data/lib/active_record/scoping/default.rb +142 -0
- data/lib/active_record/scoping/named.rb +200 -0
- data/lib/active_record/scoping.rb +152 -0
- data/lib/active_record/serialization.rb +8 -91
- data/lib/active_record/serializers/xml_serializer.rb +43 -197
- data/lib/active_record/session_store.rb +129 -103
- data/lib/active_record/store.rb +52 -0
- data/lib/active_record/test_case.rb +30 -23
- data/lib/active_record/timestamp.rb +95 -52
- data/lib/active_record/transactions.rb +212 -66
- data/lib/active_record/translation.rb +22 -0
- data/lib/active_record/validations/associated.rb +43 -0
- data/lib/active_record/validations/uniqueness.rb +180 -0
- data/lib/active_record/validations.rb +43 -1106
- data/lib/active_record/version.rb +5 -4
- data/lib/active_record.rb +121 -48
- data/lib/rails/generators/active_record/migration/migration_generator.rb +25 -0
- data/lib/rails/generators/active_record/migration/templates/migration.rb +34 -0
- data/lib/rails/generators/active_record/migration.rb +15 -0
- data/lib/rails/generators/active_record/model/model_generator.rb +47 -0
- data/lib/rails/generators/active_record/model/templates/migration.rb +15 -0
- data/lib/rails/generators/active_record/model/templates/model.rb +12 -0
- data/lib/rails/generators/active_record/model/templates/module.rb +7 -0
- data/lib/rails/generators/active_record/observer/observer_generator.rb +15 -0
- data/lib/rails/generators/active_record/observer/templates/observer.rb +4 -0
- data/lib/rails/generators/active_record/session_migration/session_migration_generator.rb +25 -0
- data/lib/rails/generators/active_record/session_migration/templates/migration.rb +12 -0
- data/lib/rails/generators/active_record.rb +25 -0
- metadata +187 -363
- data/CHANGELOG +0 -5904
- data/README +0 -351
- data/RUNNING_UNIT_TESTS +0 -36
- data/Rakefile +0 -268
- data/install.rb +0 -30
- data/lib/active_record/association_preload.rb +0 -406
- data/lib/active_record/associations/association_collection.rb +0 -533
- data/lib/active_record/associations/association_proxy.rb +0 -288
- data/lib/active_record/batches.rb +0 -85
- data/lib/active_record/calculations.rb +0 -321
- data/lib/active_record/dirty.rb +0 -183
- data/lib/active_record/named_scope.rb +0 -197
- data/lib/active_record/serializers/json_serializer.rb +0 -91
- data/lib/activerecord.rb +0 -2
- data/test/assets/example.log +0 -1
- data/test/assets/flowers.jpg +0 -0
- data/test/cases/aaa_create_tables_test.rb +0 -24
- data/test/cases/active_schema_test_mysql.rb +0 -122
- data/test/cases/active_schema_test_postgresql.rb +0 -24
- data/test/cases/adapter_test.rb +0 -144
- data/test/cases/aggregations_test.rb +0 -167
- data/test/cases/ar_schema_test.rb +0 -32
- data/test/cases/associations/belongs_to_associations_test.rb +0 -438
- data/test/cases/associations/callbacks_test.rb +0 -161
- data/test/cases/associations/cascaded_eager_loading_test.rb +0 -131
- data/test/cases/associations/eager_load_includes_full_sti_class_test.rb +0 -36
- data/test/cases/associations/eager_load_nested_include_test.rb +0 -131
- data/test/cases/associations/eager_load_nested_polymorphic_include.rb +0 -19
- data/test/cases/associations/eager_singularization_test.rb +0 -145
- data/test/cases/associations/eager_test.rb +0 -852
- data/test/cases/associations/extension_test.rb +0 -62
- data/test/cases/associations/habtm_join_table_test.rb +0 -56
- data/test/cases/associations/has_and_belongs_to_many_associations_test.rb +0 -827
- data/test/cases/associations/has_many_associations_test.rb +0 -1273
- data/test/cases/associations/has_many_through_associations_test.rb +0 -360
- data/test/cases/associations/has_one_associations_test.rb +0 -330
- data/test/cases/associations/has_one_through_associations_test.rb +0 -209
- data/test/cases/associations/inner_join_association_test.rb +0 -93
- data/test/cases/associations/inverse_associations_test.rb +0 -566
- data/test/cases/associations/join_model_test.rb +0 -712
- data/test/cases/associations_test.rb +0 -282
- data/test/cases/attribute_methods_test.rb +0 -305
- data/test/cases/autosave_association_test.rb +0 -1218
- data/test/cases/base_test.rb +0 -2166
- data/test/cases/batches_test.rb +0 -81
- data/test/cases/binary_test.rb +0 -30
- data/test/cases/calculations_test.rb +0 -360
- data/test/cases/callbacks_observers_test.rb +0 -38
- data/test/cases/callbacks_test.rb +0 -438
- data/test/cases/class_inheritable_attributes_test.rb +0 -32
- data/test/cases/column_alias_test.rb +0 -17
- data/test/cases/column_definition_test.rb +0 -70
- data/test/cases/connection_pool_test.rb +0 -25
- data/test/cases/connection_test_firebird.rb +0 -8
- data/test/cases/connection_test_mysql.rb +0 -65
- data/test/cases/copy_table_test_sqlite.rb +0 -80
- data/test/cases/counter_cache_test.rb +0 -84
- data/test/cases/database_statements_test.rb +0 -12
- data/test/cases/datatype_test_postgresql.rb +0 -204
- data/test/cases/date_time_test.rb +0 -37
- data/test/cases/default_test_firebird.rb +0 -16
- data/test/cases/defaults_test.rb +0 -111
- data/test/cases/deprecated_finder_test.rb +0 -30
- data/test/cases/dirty_test.rb +0 -316
- data/test/cases/finder_respond_to_test.rb +0 -76
- data/test/cases/finder_test.rb +0 -1098
- data/test/cases/fixtures_test.rb +0 -661
- data/test/cases/helper.rb +0 -68
- data/test/cases/i18n_test.rb +0 -46
- data/test/cases/inheritance_test.rb +0 -262
- data/test/cases/invalid_date_test.rb +0 -24
- data/test/cases/json_serialization_test.rb +0 -219
- data/test/cases/lifecycle_test.rb +0 -193
- data/test/cases/locking_test.rb +0 -350
- data/test/cases/method_scoping_test.rb +0 -704
- data/test/cases/migration_test.rb +0 -1649
- data/test/cases/migration_test_firebird.rb +0 -124
- data/test/cases/mixin_test.rb +0 -96
- data/test/cases/modules_test.rb +0 -109
- data/test/cases/multiple_db_test.rb +0 -85
- data/test/cases/named_scope_test.rb +0 -372
- data/test/cases/nested_attributes_test.rb +0 -840
- data/test/cases/pk_test.rb +0 -119
- data/test/cases/pooled_connections_test.rb +0 -103
- data/test/cases/query_cache_test.rb +0 -129
- data/test/cases/readonly_test.rb +0 -107
- data/test/cases/reflection_test.rb +0 -234
- data/test/cases/reload_models_test.rb +0 -22
- data/test/cases/repair_helper.rb +0 -50
- data/test/cases/reserved_word_test_mysql.rb +0 -176
- data/test/cases/sanitize_test.rb +0 -25
- data/test/cases/schema_authorization_test_postgresql.rb +0 -75
- data/test/cases/schema_dumper_test.rb +0 -211
- data/test/cases/schema_test_postgresql.rb +0 -178
- data/test/cases/serialization_test.rb +0 -47
- data/test/cases/sp_test_mysql.rb +0 -16
- data/test/cases/synonym_test_oracle.rb +0 -17
- data/test/cases/timestamp_test.rb +0 -75
- data/test/cases/transactions_test.rb +0 -543
- data/test/cases/unconnected_test.rb +0 -32
- data/test/cases/validations_i18n_test.rb +0 -925
- data/test/cases/validations_test.rb +0 -1684
- data/test/cases/xml_serialization_test.rb +0 -240
- data/test/cases/yaml_serialization_test.rb +0 -11
- data/test/config.rb +0 -5
- data/test/connections/jdbc_jdbcderby/connection.rb +0 -18
- data/test/connections/jdbc_jdbch2/connection.rb +0 -18
- data/test/connections/jdbc_jdbchsqldb/connection.rb +0 -18
- data/test/connections/jdbc_jdbcmysql/connection.rb +0 -26
- data/test/connections/jdbc_jdbcpostgresql/connection.rb +0 -26
- data/test/connections/jdbc_jdbcsqlite3/connection.rb +0 -25
- data/test/connections/native_db2/connection.rb +0 -25
- data/test/connections/native_firebird/connection.rb +0 -26
- data/test/connections/native_frontbase/connection.rb +0 -27
- data/test/connections/native_mysql/connection.rb +0 -25
- data/test/connections/native_openbase/connection.rb +0 -21
- data/test/connections/native_oracle/connection.rb +0 -27
- data/test/connections/native_postgresql/connection.rb +0 -21
- data/test/connections/native_sqlite/connection.rb +0 -25
- data/test/connections/native_sqlite3/connection.rb +0 -25
- data/test/connections/native_sqlite3/in_memory_connection.rb +0 -18
- data/test/connections/native_sybase/connection.rb +0 -23
- data/test/fixtures/accounts.yml +0 -29
- data/test/fixtures/all/developers.yml +0 -0
- data/test/fixtures/all/people.csv +0 -0
- data/test/fixtures/all/tasks.yml +0 -0
- data/test/fixtures/author_addresses.yml +0 -5
- data/test/fixtures/author_favorites.yml +0 -4
- data/test/fixtures/authors.yml +0 -9
- data/test/fixtures/binaries.yml +0 -132
- data/test/fixtures/books.yml +0 -7
- data/test/fixtures/categories/special_categories.yml +0 -9
- data/test/fixtures/categories/subsubdir/arbitrary_filename.yml +0 -4
- data/test/fixtures/categories.yml +0 -14
- data/test/fixtures/categories_ordered.yml +0 -7
- data/test/fixtures/categories_posts.yml +0 -23
- data/test/fixtures/categorizations.yml +0 -17
- data/test/fixtures/clubs.yml +0 -6
- data/test/fixtures/comments.yml +0 -59
- data/test/fixtures/companies.yml +0 -56
- data/test/fixtures/computers.yml +0 -4
- data/test/fixtures/courses.yml +0 -7
- data/test/fixtures/customers.yml +0 -26
- data/test/fixtures/developers.yml +0 -21
- data/test/fixtures/developers_projects.yml +0 -17
- data/test/fixtures/edges.yml +0 -6
- data/test/fixtures/entrants.yml +0 -14
- data/test/fixtures/faces.yml +0 -11
- data/test/fixtures/fk_test_has_fk.yml +0 -3
- data/test/fixtures/fk_test_has_pk.yml +0 -2
- data/test/fixtures/funny_jokes.yml +0 -10
- data/test/fixtures/interests.yml +0 -33
- data/test/fixtures/items.yml +0 -4
- data/test/fixtures/jobs.yml +0 -7
- data/test/fixtures/legacy_things.yml +0 -3
- data/test/fixtures/mateys.yml +0 -4
- data/test/fixtures/member_types.yml +0 -6
- data/test/fixtures/members.yml +0 -6
- data/test/fixtures/memberships.yml +0 -20
- data/test/fixtures/men.yml +0 -5
- data/test/fixtures/minimalistics.yml +0 -2
- data/test/fixtures/mixed_case_monkeys.yml +0 -6
- data/test/fixtures/mixins.yml +0 -29
- data/test/fixtures/movies.yml +0 -7
- data/test/fixtures/naked/csv/accounts.csv +0 -1
- data/test/fixtures/naked/yml/accounts.yml +0 -1
- data/test/fixtures/naked/yml/companies.yml +0 -1
- data/test/fixtures/naked/yml/courses.yml +0 -1
- data/test/fixtures/organizations.yml +0 -5
- data/test/fixtures/owners.yml +0 -7
- data/test/fixtures/parrots.yml +0 -27
- data/test/fixtures/parrots_pirates.yml +0 -7
- data/test/fixtures/people.yml +0 -15
- data/test/fixtures/pets.yml +0 -14
- data/test/fixtures/pirates.yml +0 -9
- data/test/fixtures/polymorphic_designs.yml +0 -19
- data/test/fixtures/polymorphic_prices.yml +0 -19
- data/test/fixtures/posts.yml +0 -52
- data/test/fixtures/price_estimates.yml +0 -7
- data/test/fixtures/projects.yml +0 -7
- data/test/fixtures/readers.yml +0 -9
- data/test/fixtures/references.yml +0 -17
- data/test/fixtures/reserved_words/distinct.yml +0 -5
- data/test/fixtures/reserved_words/distincts_selects.yml +0 -11
- data/test/fixtures/reserved_words/group.yml +0 -14
- data/test/fixtures/reserved_words/select.yml +0 -8
- data/test/fixtures/reserved_words/values.yml +0 -7
- data/test/fixtures/ships.yml +0 -5
- data/test/fixtures/sponsors.yml +0 -9
- data/test/fixtures/subscribers.yml +0 -7
- data/test/fixtures/subscriptions.yml +0 -12
- data/test/fixtures/taggings.yml +0 -28
- data/test/fixtures/tags.yml +0 -7
- data/test/fixtures/tasks.yml +0 -7
- data/test/fixtures/tees.yml +0 -4
- data/test/fixtures/ties.yml +0 -4
- data/test/fixtures/topics.yml +0 -42
- data/test/fixtures/toys.yml +0 -4
- data/test/fixtures/treasures.yml +0 -10
- data/test/fixtures/vertices.yml +0 -4
- data/test/fixtures/warehouse-things.yml +0 -3
- data/test/fixtures/zines.yml +0 -5
- data/test/migrations/broken/100_migration_that_raises_exception.rb +0 -10
- data/test/migrations/decimal/1_give_me_big_numbers.rb +0 -15
- data/test/migrations/duplicate/1_people_have_last_names.rb +0 -9
- data/test/migrations/duplicate/2_we_need_reminders.rb +0 -12
- data/test/migrations/duplicate/3_foo.rb +0 -7
- data/test/migrations/duplicate/3_innocent_jointable.rb +0 -12
- data/test/migrations/duplicate_names/20080507052938_chunky.rb +0 -7
- data/test/migrations/duplicate_names/20080507053028_chunky.rb +0 -7
- data/test/migrations/interleaved/pass_1/3_innocent_jointable.rb +0 -12
- data/test/migrations/interleaved/pass_2/1_people_have_last_names.rb +0 -9
- data/test/migrations/interleaved/pass_2/3_innocent_jointable.rb +0 -12
- data/test/migrations/interleaved/pass_3/1_people_have_last_names.rb +0 -9
- data/test/migrations/interleaved/pass_3/2_i_raise_on_down.rb +0 -8
- data/test/migrations/interleaved/pass_3/3_innocent_jointable.rb +0 -12
- data/test/migrations/missing/1000_people_have_middle_names.rb +0 -9
- data/test/migrations/missing/1_people_have_last_names.rb +0 -9
- data/test/migrations/missing/3_we_need_reminders.rb +0 -12
- data/test/migrations/missing/4_innocent_jointable.rb +0 -12
- data/test/migrations/valid/1_people_have_last_names.rb +0 -9
- data/test/migrations/valid/2_we_need_reminders.rb +0 -12
- data/test/migrations/valid/3_innocent_jointable.rb +0 -12
- data/test/models/author.rb +0 -151
- data/test/models/auto_id.rb +0 -4
- data/test/models/binary.rb +0 -2
- data/test/models/bird.rb +0 -9
- data/test/models/book.rb +0 -4
- data/test/models/categorization.rb +0 -5
- data/test/models/category.rb +0 -34
- data/test/models/citation.rb +0 -6
- data/test/models/club.rb +0 -13
- data/test/models/column_name.rb +0 -3
- data/test/models/comment.rb +0 -29
- data/test/models/company.rb +0 -173
- data/test/models/company_in_module.rb +0 -78
- data/test/models/computer.rb +0 -3
- data/test/models/contact.rb +0 -16
- data/test/models/contract.rb +0 -5
- data/test/models/course.rb +0 -3
- data/test/models/customer.rb +0 -73
- data/test/models/default.rb +0 -2
- data/test/models/developer.rb +0 -101
- data/test/models/edge.rb +0 -5
- data/test/models/entrant.rb +0 -3
- data/test/models/essay.rb +0 -3
- data/test/models/event.rb +0 -3
- data/test/models/event_author.rb +0 -8
- data/test/models/face.rb +0 -7
- data/test/models/guid.rb +0 -2
- data/test/models/interest.rb +0 -5
- data/test/models/invoice.rb +0 -4
- data/test/models/item.rb +0 -7
- data/test/models/job.rb +0 -5
- data/test/models/joke.rb +0 -3
- data/test/models/keyboard.rb +0 -3
- data/test/models/legacy_thing.rb +0 -3
- data/test/models/line_item.rb +0 -3
- data/test/models/man.rb +0 -9
- data/test/models/matey.rb +0 -4
- data/test/models/member.rb +0 -12
- data/test/models/member_detail.rb +0 -5
- data/test/models/member_type.rb +0 -3
- data/test/models/membership.rb +0 -9
- data/test/models/minimalistic.rb +0 -2
- data/test/models/mixed_case_monkey.rb +0 -3
- data/test/models/movie.rb +0 -5
- data/test/models/order.rb +0 -4
- data/test/models/organization.rb +0 -6
- data/test/models/owner.rb +0 -5
- data/test/models/parrot.rb +0 -22
- data/test/models/person.rb +0 -16
- data/test/models/pet.rb +0 -5
- data/test/models/pirate.rb +0 -80
- data/test/models/polymorphic_design.rb +0 -3
- data/test/models/polymorphic_price.rb +0 -3
- data/test/models/post.rb +0 -102
- data/test/models/price_estimate.rb +0 -3
- data/test/models/project.rb +0 -30
- data/test/models/reader.rb +0 -4
- data/test/models/reference.rb +0 -4
- data/test/models/reply.rb +0 -46
- data/test/models/ship.rb +0 -19
- data/test/models/ship_part.rb +0 -7
- data/test/models/sponsor.rb +0 -4
- data/test/models/subject.rb +0 -4
- data/test/models/subscriber.rb +0 -8
- data/test/models/subscription.rb +0 -4
- data/test/models/tag.rb +0 -7
- data/test/models/tagging.rb +0 -10
- data/test/models/task.rb +0 -3
- data/test/models/tee.rb +0 -4
- data/test/models/tie.rb +0 -4
- data/test/models/topic.rb +0 -80
- data/test/models/toy.rb +0 -6
- data/test/models/treasure.rb +0 -8
- data/test/models/vertex.rb +0 -9
- data/test/models/warehouse_thing.rb +0 -5
- data/test/models/zine.rb +0 -3
- data/test/schema/mysql_specific_schema.rb +0 -31
- data/test/schema/postgresql_specific_schema.rb +0 -114
- data/test/schema/schema.rb +0 -550
- data/test/schema/schema2.rb +0 -6
- data/test/schema/sqlite_specific_schema.rb +0 -25
@@ -1,6 +1,9 @@
|
|
1
1
|
module ActiveRecord
|
2
|
-
#
|
2
|
+
# = Active Record RecordInvalid
|
3
|
+
#
|
4
|
+
# Raised by <tt>save!</tt> and <tt>create!</tt> when the record is invalid. Use the
|
3
5
|
# +record+ method to retrieve the record which did not validate.
|
6
|
+
#
|
4
7
|
# begin
|
5
8
|
# complex_operation_that_calls_save!_internally
|
6
9
|
# rescue ActiveRecord::RecordInvalid => invalid
|
@@ -10,1137 +13,71 @@ module ActiveRecord
|
|
10
13
|
attr_reader :record
|
11
14
|
def initialize(record)
|
12
15
|
@record = record
|
13
|
-
errors = @record.errors.full_messages.join(
|
14
|
-
super(I18n.t(
|
15
|
-
end
|
16
|
-
end
|
17
|
-
|
18
|
-
class Error
|
19
|
-
attr_accessor :base, :attribute, :type, :message, :options
|
20
|
-
|
21
|
-
def initialize(base, attribute, type = nil, options = {})
|
22
|
-
self.base = base
|
23
|
-
self.attribute = attribute
|
24
|
-
self.type = type || :invalid
|
25
|
-
self.options = options
|
26
|
-
self.message = options.delete(:message) || self.type
|
27
|
-
end
|
28
|
-
|
29
|
-
def message
|
30
|
-
# When type is a string, it means that we do not have to do a lookup, because
|
31
|
-
# the user already sent the "final" message.
|
32
|
-
type.is_a?(String) ? type : generate_message(default_options)
|
33
|
-
end
|
34
|
-
|
35
|
-
def full_message
|
36
|
-
attribute.to_s == 'base' ? message : generate_full_message(default_options)
|
37
|
-
end
|
38
|
-
|
39
|
-
alias :to_s :message
|
40
|
-
|
41
|
-
def value
|
42
|
-
@base.respond_to?(attribute) ? @base.send(attribute) : nil
|
16
|
+
errors = @record.errors.full_messages.join(", ")
|
17
|
+
super(I18n.t("activerecord.errors.messages.record_invalid", :errors => errors))
|
43
18
|
end
|
44
|
-
|
45
|
-
protected
|
46
|
-
|
47
|
-
# Translates an error message in it's default scope (<tt>activerecord.errrors.messages</tt>).
|
48
|
-
# Error messages are first looked up in <tt>models.MODEL.attributes.ATTRIBUTE.MESSAGE</tt>, if it's not there,
|
49
|
-
# it's looked up in <tt>models.MODEL.MESSAGE</tt> and if that is not there it returns the translation of the
|
50
|
-
# default message (e.g. <tt>activerecord.errors.messages.MESSAGE</tt>). The translated model name,
|
51
|
-
# translated attribute name and the value are available for interpolation.
|
52
|
-
#
|
53
|
-
# When using inheritence in your models, it will check all the inherited models too, but only if the model itself
|
54
|
-
# hasn't been found. Say you have <tt>class Admin < User; end</tt> and you wanted the translation for the <tt>:blank</tt>
|
55
|
-
# error +message+ for the <tt>title</tt> +attribute+, it looks for these translations:
|
56
|
-
#
|
57
|
-
# <ol>
|
58
|
-
# <li><tt>activerecord.errors.models.admin.attributes.title.blank</tt></li>
|
59
|
-
# <li><tt>activerecord.errors.models.admin.blank</tt></li>
|
60
|
-
# <li><tt>activerecord.errors.models.user.attributes.title.blank</tt></li>
|
61
|
-
# <li><tt>activerecord.errors.models.user.blank</tt></li>
|
62
|
-
# <li><tt>activerecord.errors.messages.blank</tt></li>
|
63
|
-
# <li>any default you provided through the +options+ hash (in the activerecord.errors scope)</li>
|
64
|
-
# </ol>
|
65
|
-
def generate_message(options = {})
|
66
|
-
keys = @base.class.self_and_descendants_from_active_record.map do |klass|
|
67
|
-
[ :"models.#{klass.name.underscore}.attributes.#{attribute}.#{@message}",
|
68
|
-
:"models.#{klass.name.underscore}.#{@message}" ]
|
69
|
-
end.flatten
|
70
|
-
|
71
|
-
keys << options.delete(:default)
|
72
|
-
keys << :"messages.#{@message}"
|
73
|
-
keys << @message if @message.is_a?(String)
|
74
|
-
keys << @type unless @type == @message
|
75
|
-
keys.compact!
|
76
|
-
|
77
|
-
options.merge!(:default => keys)
|
78
|
-
I18n.translate(keys.shift, options)
|
79
|
-
end
|
80
|
-
|
81
|
-
# Wraps an error message into a full_message format.
|
82
|
-
#
|
83
|
-
# The default full_message format for any locale is <tt>"%{attribute} %{message}"</tt>.
|
84
|
-
# One can specify locale specific default full_message format by storing it as a
|
85
|
-
# translation for the key <tt>:"activerecord.errors.full_messages.format"</tt>.
|
86
|
-
#
|
87
|
-
# Additionally one can specify a validation specific error message format by
|
88
|
-
# storing a translation for <tt>:"activerecord.errors.full_messages.[message_key]"</tt>.
|
89
|
-
# E.g. the full_message format for any validation that uses :blank as a message
|
90
|
-
# key (such as validates_presence_of) can be stored to <tt>:"activerecord.errors.full_messages.blank".</tt>
|
91
|
-
#
|
92
|
-
# Because the message key used by a validation can be overwritten on the
|
93
|
-
# <tt>validates_*</tt> class macro level one can customize the full_message format for
|
94
|
-
# any particular validation:
|
95
|
-
#
|
96
|
-
# # app/models/article.rb
|
97
|
-
# class Article < ActiveRecord::Base
|
98
|
-
# validates_presence_of :title, :message => :"title.blank"
|
99
|
-
# end
|
100
|
-
#
|
101
|
-
# # config/locales/en.yml
|
102
|
-
# en:
|
103
|
-
# activerecord:
|
104
|
-
# errors:
|
105
|
-
# full_messages:
|
106
|
-
# title:
|
107
|
-
# blank: This title is screwed!
|
108
|
-
def generate_full_message(options = {})
|
109
|
-
keys = [
|
110
|
-
:"full_messages.#{@message}",
|
111
|
-
:'full_messages.format',
|
112
|
-
'%{attribute} %{message}'
|
113
|
-
]
|
114
|
-
|
115
|
-
options.merge!(:default => keys, :message => self.message)
|
116
|
-
I18n.translate(keys.shift, options)
|
117
|
-
end
|
118
|
-
|
119
|
-
# Return user options with default options.
|
120
|
-
#
|
121
|
-
def default_options
|
122
|
-
options.reverse_merge :scope => [:activerecord, :errors],
|
123
|
-
:model => @base.class.human_name,
|
124
|
-
:attribute => @base.class.human_attribute_name(attribute.to_s),
|
125
|
-
:value => value
|
126
|
-
end
|
127
19
|
end
|
128
20
|
|
129
|
-
# Active Record
|
130
|
-
# determine whether the object is in a valid state to be saved. See usage example in Validations.
|
131
|
-
class Errors
|
132
|
-
include Enumerable
|
133
|
-
|
134
|
-
class << self
|
135
|
-
def default_error_messages
|
136
|
-
ActiveSupport::Deprecation.warn("ActiveRecord::Errors.default_error_messages has been deprecated. Please use I18n.translate('activerecord.errors.messages').")
|
137
|
-
I18n.translate 'activerecord.errors.messages'
|
138
|
-
end
|
139
|
-
end
|
140
|
-
|
141
|
-
def initialize(base) # :nodoc:
|
142
|
-
@base = base
|
143
|
-
clear
|
144
|
-
end
|
145
|
-
|
146
|
-
# Adds an error to the base object instead of any particular attribute. This is used
|
147
|
-
# to report errors that don't tie to any specific attribute, but rather to the object
|
148
|
-
# as a whole. These error messages don't get prepended with any field name when iterating
|
149
|
-
# with +each_full+, so they should be complete sentences.
|
150
|
-
def add_to_base(msg)
|
151
|
-
add(:base, msg)
|
152
|
-
end
|
153
|
-
|
154
|
-
# Adds an error message (+messsage+) to the +attribute+, which will be returned on a call to <tt>on(attribute)</tt>
|
155
|
-
# for the same attribute and ensure that this error object returns false when asked if <tt>empty?</tt>. More than one
|
156
|
-
# error can be added to the same +attribute+ in which case an array will be returned on a call to <tt>on(attribute)</tt>.
|
157
|
-
# If no +messsage+ is supplied, :invalid is assumed.
|
158
|
-
# If +message+ is a Symbol, it will be translated, using the appropriate scope (see translate_error).
|
159
|
-
#
|
160
|
-
def add(attribute, message = nil, options = {})
|
161
|
-
options[:message] = options.delete(:default) if options[:default].is_a?(Symbol)
|
162
|
-
error, message = message, nil if message.is_a?(Error)
|
163
|
-
|
164
|
-
@errors[attribute.to_s] ||= []
|
165
|
-
@errors[attribute.to_s] << (error || Error.new(@base, attribute, message, options))
|
166
|
-
end
|
167
|
-
|
168
|
-
# Will add an error message to each of the attributes in +attributes+ that is empty.
|
169
|
-
def add_on_empty(attributes, custom_message = nil)
|
170
|
-
for attr in [attributes].flatten
|
171
|
-
value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
|
172
|
-
is_empty = value.respond_to?(:empty?) ? value.empty? : false
|
173
|
-
add(attr, :empty, :default => custom_message) unless !value.nil? && !is_empty
|
174
|
-
end
|
175
|
-
end
|
176
|
-
|
177
|
-
# Will add an error message to each of the attributes in +attributes+ that is blank (using Object#blank?).
|
178
|
-
def add_on_blank(attributes, custom_message = nil)
|
179
|
-
for attr in [attributes].flatten
|
180
|
-
value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
|
181
|
-
add(attr, :blank, :default => custom_message) if value.blank?
|
182
|
-
end
|
183
|
-
end
|
184
|
-
|
185
|
-
# Returns true if the specified +attribute+ has errors associated with it.
|
186
|
-
#
|
187
|
-
# class Company < ActiveRecord::Base
|
188
|
-
# validates_presence_of :name, :address, :email
|
189
|
-
# validates_length_of :name, :in => 5..30
|
190
|
-
# end
|
191
|
-
#
|
192
|
-
# company = Company.create(:address => '123 First St.')
|
193
|
-
# company.errors.invalid?(:name) # => true
|
194
|
-
# company.errors.invalid?(:address) # => false
|
195
|
-
def invalid?(attribute)
|
196
|
-
!@errors[attribute.to_s].nil?
|
197
|
-
end
|
198
|
-
|
199
|
-
# Returns +nil+, if no errors are associated with the specified +attribute+.
|
200
|
-
# Returns the error message, if one error is associated with the specified +attribute+.
|
201
|
-
# Returns an array of error messages, if more than one error is associated with the specified +attribute+.
|
202
|
-
#
|
203
|
-
# class Company < ActiveRecord::Base
|
204
|
-
# validates_presence_of :name, :address, :email
|
205
|
-
# validates_length_of :name, :in => 5..30
|
206
|
-
# end
|
207
|
-
#
|
208
|
-
# company = Company.create(:address => '123 First St.')
|
209
|
-
# company.errors.on(:name) # => ["is too short (minimum is 5 characters)", "can't be blank"]
|
210
|
-
# company.errors.on(:email) # => "can't be blank"
|
211
|
-
# company.errors.on(:address) # => nil
|
212
|
-
def on(attribute)
|
213
|
-
attribute = attribute.to_s
|
214
|
-
return nil unless @errors.has_key?(attribute)
|
215
|
-
errors = @errors[attribute].map(&:to_s)
|
216
|
-
errors.size == 1 ? errors.first : errors
|
217
|
-
end
|
218
|
-
|
219
|
-
alias :[] :on
|
220
|
-
|
221
|
-
# Returns errors assigned to the base object through +add_to_base+ according to the normal rules of <tt>on(attribute)</tt>.
|
222
|
-
def on_base
|
223
|
-
on(:base)
|
224
|
-
end
|
225
|
-
|
226
|
-
# Yields each attribute and associated message per error added.
|
227
|
-
#
|
228
|
-
# class Company < ActiveRecord::Base
|
229
|
-
# validates_presence_of :name, :address, :email
|
230
|
-
# validates_length_of :name, :in => 5..30
|
231
|
-
# end
|
232
|
-
#
|
233
|
-
# company = Company.create(:address => '123 First St.')
|
234
|
-
# company.errors.each{|attr,msg| puts "#{attr} - #{msg}" }
|
235
|
-
# # => name - is too short (minimum is 5 characters)
|
236
|
-
# # name - can't be blank
|
237
|
-
# # address - can't be blank
|
238
|
-
def each
|
239
|
-
@errors.each_key { |attr| @errors[attr].each { |error| yield attr, error.message } }
|
240
|
-
end
|
241
|
-
|
242
|
-
# Yields each attribute and associated error per error added.
|
243
|
-
#
|
244
|
-
# class Company < ActiveRecord::Base
|
245
|
-
# validates_presence_of :name, :address, :email
|
246
|
-
# validates_length_of :name, :in => 5..30
|
247
|
-
# end
|
248
|
-
#
|
249
|
-
# company = Company.create(:address => '123 First St.')
|
250
|
-
# company.errors.each_error{|attr,err| puts "#{attr} - #{err.type}" }
|
251
|
-
# # => name - :too_short
|
252
|
-
# # name - :blank
|
253
|
-
# # address - :blank
|
254
|
-
def each_error
|
255
|
-
@errors.each_key { |attr| @errors[attr].each { |error| yield attr, error } }
|
256
|
-
end
|
257
|
-
|
258
|
-
# Yields each full error message added. So <tt>Person.errors.add("first_name", "can't be empty")</tt> will be returned
|
259
|
-
# through iteration as "First name can't be empty".
|
260
|
-
#
|
261
|
-
# class Company < ActiveRecord::Base
|
262
|
-
# validates_presence_of :name, :address, :email
|
263
|
-
# validates_length_of :name, :in => 5..30
|
264
|
-
# end
|
265
|
-
#
|
266
|
-
# company = Company.create(:address => '123 First St.')
|
267
|
-
# company.errors.each_full{|msg| puts msg }
|
268
|
-
# # => Name is too short (minimum is 5 characters)
|
269
|
-
# # Name can't be blank
|
270
|
-
# # Address can't be blank
|
271
|
-
def each_full
|
272
|
-
full_messages.each { |msg| yield msg }
|
273
|
-
end
|
274
|
-
|
275
|
-
# Returns all the full error messages in an array.
|
276
|
-
#
|
277
|
-
# class Company < ActiveRecord::Base
|
278
|
-
# validates_presence_of :name, :address, :email
|
279
|
-
# validates_length_of :name, :in => 5..30
|
280
|
-
# end
|
281
|
-
#
|
282
|
-
# company = Company.create(:address => '123 First St.')
|
283
|
-
# company.errors.full_messages # =>
|
284
|
-
# ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Address can't be blank"]
|
285
|
-
def full_messages(options = {})
|
286
|
-
@errors.values.inject([]) do |full_messages, errors|
|
287
|
-
full_messages + errors.map { |error| error.full_message }
|
288
|
-
end
|
289
|
-
end
|
290
|
-
|
291
|
-
# Returns true if no errors have been added.
|
292
|
-
def empty?
|
293
|
-
@errors.empty?
|
294
|
-
end
|
295
|
-
|
296
|
-
# Removes all errors that have been added.
|
297
|
-
def clear
|
298
|
-
@errors = ActiveSupport::OrderedHash.new
|
299
|
-
end
|
300
|
-
|
301
|
-
# Returns the total number of errors added. Two errors added to the same attribute will be counted as such.
|
302
|
-
def size
|
303
|
-
@errors.values.inject(0) { |error_count, attribute| error_count + attribute.size }
|
304
|
-
end
|
305
|
-
|
306
|
-
alias_method :count, :size
|
307
|
-
alias_method :length, :size
|
308
|
-
|
309
|
-
# Returns an XML representation of this error object.
|
310
|
-
#
|
311
|
-
# class Company < ActiveRecord::Base
|
312
|
-
# validates_presence_of :name, :address, :email
|
313
|
-
# validates_length_of :name, :in => 5..30
|
314
|
-
# end
|
315
|
-
#
|
316
|
-
# company = Company.create(:address => '123 First St.')
|
317
|
-
# company.errors.to_xml
|
318
|
-
# # => <?xml version="1.0" encoding="UTF-8"?>
|
319
|
-
# # <errors>
|
320
|
-
# # <error>Name is too short (minimum is 5 characters)</error>
|
321
|
-
# # <error>Name can't be blank</error>
|
322
|
-
# # <error>Address can't be blank</error>
|
323
|
-
# # </errors>
|
324
|
-
def to_xml(options={})
|
325
|
-
options[:root] ||= "errors"
|
326
|
-
options[:indent] ||= 2
|
327
|
-
options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
|
328
|
-
|
329
|
-
options[:builder].instruct! unless options.delete(:skip_instruct)
|
330
|
-
options[:builder].errors do |e|
|
331
|
-
full_messages.each { |msg| e.error(msg) }
|
332
|
-
end
|
333
|
-
end
|
334
|
-
|
335
|
-
def generate_message(attribute, message = :invalid, options = {})
|
336
|
-
Error.new(@base, attribute, message, options).to_s
|
337
|
-
end
|
338
|
-
end
|
339
|
-
|
340
|
-
|
341
|
-
# Please do have a look at ActiveRecord::Validations::ClassMethods for a higher level of validations.
|
342
|
-
#
|
343
|
-
# Active Records implement validation by overwriting Base#validate (or the variations, +validate_on_create+ and
|
344
|
-
# +validate_on_update+). Each of these methods can inspect the state of the object, which usually means ensuring
|
345
|
-
# that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).
|
346
|
-
#
|
347
|
-
# Example:
|
21
|
+
# = Active Record Validations
|
348
22
|
#
|
349
|
-
#
|
350
|
-
#
|
351
|
-
#
|
352
|
-
#
|
353
|
-
#
|
354
|
-
# end
|
355
|
-
#
|
356
|
-
# def validate_on_create # is only run the first time a new object is saved
|
357
|
-
# unless valid_discount?(membership_discount)
|
358
|
-
# errors.add("membership_discount", "has expired")
|
359
|
-
# end
|
360
|
-
# end
|
361
|
-
#
|
362
|
-
# def validate_on_update
|
363
|
-
# errors.add_to_base("No changes have occurred") if unchanged_attributes?
|
364
|
-
# end
|
365
|
-
# end
|
366
|
-
#
|
367
|
-
# person = Person.new("first_name" => "David", "phone_number" => "what?")
|
368
|
-
# person.save # => false (and doesn't do the save)
|
369
|
-
# person.errors.empty? # => false
|
370
|
-
# person.errors.count # => 2
|
371
|
-
# person.errors.on "last_name" # => "can't be empty"
|
372
|
-
# person.errors.on "phone_number" # => "has invalid format"
|
373
|
-
# person.errors.each_full { |msg| puts msg }
|
374
|
-
# # => "Last name can't be empty\n" +
|
375
|
-
# # "Phone number has invalid format"
|
376
|
-
#
|
377
|
-
# person.attributes = { "last_name" => "Heinemeier", "phone_number" => "555-555" }
|
378
|
-
# person.save # => true (and person is now saved in the database)
|
379
|
-
#
|
380
|
-
# An Errors object is automatically created for every Active Record.
|
23
|
+
# Active Record includes the majority of its validations from <tt>ActiveModel::Validations</tt>
|
24
|
+
# all of which accept the <tt>:on</tt> argument to define the context where the
|
25
|
+
# validations are active. Active Record will always supply either the context of
|
26
|
+
# <tt>:create</tt> or <tt>:update</tt> dependent on whether the model is a
|
27
|
+
# <tt>new_record?</tt>.
|
381
28
|
module Validations
|
382
|
-
|
383
|
-
|
384
|
-
def self.included(base) # :nodoc:
|
385
|
-
base.extend ClassMethods
|
386
|
-
base.class_eval do
|
387
|
-
alias_method_chain :save, :validation
|
388
|
-
alias_method_chain :save!, :validation
|
389
|
-
end
|
390
|
-
|
391
|
-
base.send :include, ActiveSupport::Callbacks
|
392
|
-
base.define_callbacks *VALIDATIONS
|
393
|
-
end
|
29
|
+
extend ActiveSupport::Concern
|
30
|
+
include ActiveModel::Validations
|
394
31
|
|
395
|
-
# Active Record classes can implement validations in several ways. The highest level, easiest to read,
|
396
|
-
# and recommended approach is to use the declarative <tt>validates_..._of</tt> class methods (and
|
397
|
-
# +validates_associated+) documented below. These are sufficient for most model validations.
|
398
|
-
#
|
399
|
-
# Slightly lower level is +validates_each+. It provides some of the same options as the purely declarative
|
400
|
-
# validation methods, but like all the lower-level approaches it requires manually adding to the errors collection
|
401
|
-
# when the record is invalid.
|
402
|
-
#
|
403
|
-
# At a yet lower level, a model can use the class methods +validate+, +validate_on_create+ and +validate_on_update+
|
404
|
-
# to add validation methods or blocks. These are ActiveSupport::Callbacks and follow the same rules of inheritance
|
405
|
-
# and chaining.
|
406
|
-
#
|
407
|
-
# The lowest level style is to define the instance methods +validate+, +validate_on_create+ and +validate_on_update+
|
408
|
-
# as documented in ActiveRecord::Validations.
|
409
|
-
#
|
410
|
-
# == +validate+, +validate_on_create+ and +validate_on_update+ Class Methods
|
411
|
-
#
|
412
|
-
# Calls to these methods add a validation method or block to the class. Again, this approach is recommended
|
413
|
-
# only when the higher-level methods documented below (<tt>validates_..._of</tt> and +validates_associated+) are
|
414
|
-
# insufficient to handle the required validation.
|
415
|
-
#
|
416
|
-
# This can be done with a symbol pointing to a method:
|
417
|
-
#
|
418
|
-
# class Comment < ActiveRecord::Base
|
419
|
-
# validate :must_be_friends
|
420
|
-
#
|
421
|
-
# def must_be_friends
|
422
|
-
# errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
|
423
|
-
# end
|
424
|
-
# end
|
425
|
-
#
|
426
|
-
# Or with a block which is passed the current record to be validated:
|
427
|
-
#
|
428
|
-
# class Comment < ActiveRecord::Base
|
429
|
-
# validate do |comment|
|
430
|
-
# comment.must_be_friends
|
431
|
-
# end
|
432
|
-
#
|
433
|
-
# def must_be_friends
|
434
|
-
# errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
|
435
|
-
# end
|
436
|
-
# end
|
437
|
-
#
|
438
|
-
# This usage applies to +validate_on_create+ and +validate_on_update+ as well.
|
439
32
|
module ClassMethods
|
440
|
-
|
441
|
-
:on => :save,
|
442
|
-
:allow_nil => false,
|
443
|
-
:allow_blank => false,
|
444
|
-
:message => nil
|
445
|
-
}.freeze
|
446
|
-
|
447
|
-
ALL_RANGE_OPTIONS = [ :is, :within, :in, :minimum, :maximum ].freeze
|
448
|
-
ALL_NUMERICALITY_CHECKS = { :greater_than => '>', :greater_than_or_equal_to => '>=',
|
449
|
-
:equal_to => '==', :less_than => '<', :less_than_or_equal_to => '<=',
|
450
|
-
:odd => 'odd?', :even => 'even?' }.freeze
|
451
|
-
|
452
|
-
# Validates each attribute against a block.
|
453
|
-
#
|
454
|
-
# class Person < ActiveRecord::Base
|
455
|
-
# validates_each :first_name, :last_name do |record, attr, value|
|
456
|
-
# record.errors.add attr, 'starts with z.' if value[0] == ?z
|
457
|
-
# end
|
458
|
-
# end
|
459
|
-
#
|
460
|
-
# Options:
|
461
|
-
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
|
462
|
-
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
|
463
|
-
# * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
|
464
|
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
465
|
-
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
|
466
|
-
# method, proc or string should return or evaluate to a true or false value.
|
467
|
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
468
|
-
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
|
469
|
-
# method, proc or string should return or evaluate to a true or false value.
|
470
|
-
def validates_each(*attrs)
|
471
|
-
options = attrs.extract_options!.symbolize_keys
|
472
|
-
attrs = attrs.flatten
|
473
|
-
|
474
|
-
# Declare the validation.
|
475
|
-
send(validation_method(options[:on] || :save), options) do |record|
|
476
|
-
attrs.each do |attr|
|
477
|
-
value = record.send(attr)
|
478
|
-
next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
|
479
|
-
yield record, attr, value
|
480
|
-
end
|
481
|
-
end
|
482
|
-
end
|
483
|
-
|
484
|
-
# Encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example:
|
485
|
-
#
|
486
|
-
# Model:
|
487
|
-
# class Person < ActiveRecord::Base
|
488
|
-
# validates_confirmation_of :user_name, :password
|
489
|
-
# validates_confirmation_of :email_address, :message => "should match confirmation"
|
490
|
-
# end
|
491
|
-
#
|
492
|
-
# View:
|
493
|
-
# <%= password_field "person", "password" %>
|
494
|
-
# <%= password_field "person", "password_confirmation" %>
|
495
|
-
#
|
496
|
-
# The added +password_confirmation+ attribute is virtual; it exists only as an in-memory attribute for validating the password.
|
497
|
-
# To achieve this, the validation adds accessors to the model for the confirmation attribute. NOTE: This check is performed
|
498
|
-
# only if +password_confirmation+ is not +nil+, and by default only on save. To require confirmation, make sure to add a presence
|
499
|
-
# check for the confirmation attribute:
|
500
|
-
#
|
501
|
-
# validates_presence_of :password_confirmation, :if => :password_changed?
|
502
|
-
#
|
503
|
-
# Configuration options:
|
504
|
-
# * <tt>:message</tt> - A custom error message (default is: "doesn't match confirmation").
|
505
|
-
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
|
506
|
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
507
|
-
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
|
508
|
-
# method, proc or string should return or evaluate to a true or false value.
|
509
|
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
510
|
-
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
|
511
|
-
# method, proc or string should return or evaluate to a true or false value.
|
512
|
-
def validates_confirmation_of(*attr_names)
|
513
|
-
configuration = { :on => :save }
|
514
|
-
configuration.update(attr_names.extract_options!)
|
515
|
-
|
516
|
-
attr_accessor(*(attr_names.map { |n| "#{n}_confirmation" }))
|
517
|
-
|
518
|
-
validates_each(attr_names, configuration) do |record, attr_name, value|
|
519
|
-
unless record.send("#{attr_name}_confirmation").nil? or value == record.send("#{attr_name}_confirmation")
|
520
|
-
record.errors.add(attr_name, :confirmation, :default => configuration[:message])
|
521
|
-
end
|
522
|
-
end
|
523
|
-
end
|
524
|
-
|
525
|
-
# Encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example:
|
526
|
-
#
|
527
|
-
# class Person < ActiveRecord::Base
|
528
|
-
# validates_acceptance_of :terms_of_service
|
529
|
-
# validates_acceptance_of :eula, :message => "must be abided"
|
530
|
-
# end
|
531
|
-
#
|
532
|
-
# If the database column does not exist, the +terms_of_service+ attribute is entirely virtual. This check is
|
533
|
-
# performed only if +terms_of_service+ is not +nil+ and by default on save.
|
534
|
-
#
|
535
|
-
# Configuration options:
|
536
|
-
# * <tt>:message</tt> - A custom error message (default is: "must be accepted").
|
537
|
-
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
|
538
|
-
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is true).
|
539
|
-
# * <tt>:accept</tt> - Specifies value that is considered accepted. The default value is a string "1", which
|
540
|
-
# makes it easy to relate to an HTML checkbox. This should be set to +true+ if you are validating a database
|
541
|
-
# column, since the attribute is typecast from "1" to +true+ before validation.
|
542
|
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
543
|
-
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
|
544
|
-
# method, proc or string should return or evaluate to a true or false value.
|
545
|
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
546
|
-
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
|
547
|
-
# method, proc or string should return or evaluate to a true or false value.
|
548
|
-
def validates_acceptance_of(*attr_names)
|
549
|
-
configuration = { :on => :save, :allow_nil => true, :accept => "1" }
|
550
|
-
configuration.update(attr_names.extract_options!)
|
551
|
-
|
552
|
-
db_cols = begin
|
553
|
-
column_names
|
554
|
-
rescue Exception # To ignore both statement and connection errors
|
555
|
-
[]
|
556
|
-
end
|
557
|
-
names = attr_names.reject { |name| db_cols.include?(name.to_s) }
|
558
|
-
attr_accessor(*names)
|
559
|
-
|
560
|
-
validates_each(attr_names,configuration) do |record, attr_name, value|
|
561
|
-
unless value == configuration[:accept]
|
562
|
-
record.errors.add(attr_name, :accepted, :default => configuration[:message])
|
563
|
-
end
|
564
|
-
end
|
565
|
-
end
|
566
|
-
|
567
|
-
# Validates that the specified attributes are not blank (as defined by Object#blank?). Happens by default on save. Example:
|
568
|
-
#
|
569
|
-
# class Person < ActiveRecord::Base
|
570
|
-
# validates_presence_of :first_name
|
571
|
-
# end
|
572
|
-
#
|
573
|
-
# The first_name attribute must be in the object and it cannot be blank.
|
574
|
-
#
|
575
|
-
# If you want to validate the presence of a boolean field (where the real values are true and false),
|
576
|
-
# you will want to use <tt>validates_inclusion_of :field_name, :in => [true, false]</tt>.
|
577
|
-
#
|
578
|
-
# This is due to the way Object#blank? handles boolean values: <tt>false.blank? # => true</tt>.
|
579
|
-
#
|
580
|
-
# Configuration options:
|
581
|
-
# * <tt>message</tt> - A custom error message (default is: "can't be blank").
|
582
|
-
# * <tt>on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>,
|
583
|
-
# <tt>:update</tt>).
|
584
|
-
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
585
|
-
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).
|
586
|
-
# The method, proc or string should return or evaluate to a true or false value.
|
587
|
-
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
588
|
-
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).
|
589
|
-
# The method, proc or string should return or evaluate to a true or false value.
|
590
|
-
#
|
591
|
-
def validates_presence_of(*attr_names)
|
592
|
-
configuration = { :on => :save }
|
593
|
-
configuration.update(attr_names.extract_options!)
|
594
|
-
|
595
|
-
# can't use validates_each here, because it cannot cope with nonexistent attributes,
|
596
|
-
# while errors.add_on_empty can
|
597
|
-
send(validation_method(configuration[:on]), configuration) do |record|
|
598
|
-
record.errors.add_on_blank(attr_names, configuration[:message])
|
599
|
-
end
|
600
|
-
end
|
601
|
-
|
602
|
-
# Validates that the specified attribute matches the length restrictions supplied. Only one option can be used at a time:
|
603
|
-
#
|
604
|
-
# class Person < ActiveRecord::Base
|
605
|
-
# validates_length_of :first_name, :maximum => 30
|
606
|
-
# validates_length_of :last_name, :maximum => 30, :message => "less than %{count} if you don't mind"
|
607
|
-
# validates_length_of :fax, :in => 7..32, :allow_nil => true
|
608
|
-
# validates_length_of :phone, :in => 7..32, :allow_blank => true
|
609
|
-
# validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
|
610
|
-
# validates_length_of :zip_code, :minimum => 5, :too_short => "please enter at least %{count} characters"
|
611
|
-
# validates_length_of :smurf_leader, :is => 4, :message => "papa is spelled with %{count} characters... don't play me"
|
612
|
-
# validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least %{count} words"), :tokenizer => lambda {|str| str.scan(/\w+/) }
|
613
|
-
# end
|
614
|
-
#
|
615
|
-
# Configuration options:
|
616
|
-
# * <tt>:minimum</tt> - The minimum size of the attribute.
|
617
|
-
# * <tt>:maximum</tt> - The maximum size of the attribute.
|
618
|
-
# * <tt>:is</tt> - The exact size of the attribute.
|
619
|
-
# * <tt>:within</tt> - A range specifying the minimum and maximum size of the attribute.
|
620
|
-
# * <tt>:in</tt> - A synonym(or alias) for <tt>:within</tt>.
|
621
|
-
# * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
|
622
|
-
# * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
|
623
|
-
# * <tt>:too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is %{count} characters)").
|
624
|
-
# * <tt>:too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is %{count} characters)").
|
625
|
-
# * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt> method and the attribute is the wrong size (default is: "is the wrong length (should be %{count} characters)").
|
626
|
-
# * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>, <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
|
627
|
-
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
|
628
|
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
629
|
-
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
|
630
|
-
# method, proc or string should return or evaluate to a true or false value.
|
631
|
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
632
|
-
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
|
633
|
-
# method, proc or string should return or evaluate to a true or false value.
|
634
|
-
# * <tt>:tokenizer</tt> - Specifies how to split up the attribute string. (e.g. <tt>:tokenizer => lambda {|str| str.scan(/\w+/)}</tt> to
|
635
|
-
# count words as in above example.)
|
636
|
-
# Defaults to <tt>lambda{ |value| value.split(//) }</tt> which counts individual characters.
|
637
|
-
def validates_length_of(*attrs)
|
638
|
-
# Merge given options with defaults.
|
639
|
-
options = {
|
640
|
-
:tokenizer => lambda {|value| value.split(//)}
|
641
|
-
}.merge(DEFAULT_VALIDATION_OPTIONS)
|
642
|
-
options.update(attrs.extract_options!.symbolize_keys)
|
643
|
-
|
644
|
-
# Ensure that one and only one range option is specified.
|
645
|
-
range_options = ALL_RANGE_OPTIONS & options.keys
|
646
|
-
case range_options.size
|
647
|
-
when 0
|
648
|
-
raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.'
|
649
|
-
when 1
|
650
|
-
# Valid number of options; do nothing.
|
651
|
-
else
|
652
|
-
raise ArgumentError, 'Too many range options specified. Choose only one.'
|
653
|
-
end
|
654
|
-
|
655
|
-
# Get range option and value.
|
656
|
-
option = range_options.first
|
657
|
-
option_value = options[range_options.first]
|
658
|
-
key = {:is => :wrong_length, :minimum => :too_short, :maximum => :too_long}[option]
|
659
|
-
custom_message = options[:message] || options[key]
|
660
|
-
|
661
|
-
case option
|
662
|
-
when :within, :in
|
663
|
-
raise ArgumentError, ":#{option} must be a Range" unless option_value.is_a?(Range)
|
664
|
-
|
665
|
-
validates_each(attrs, options) do |record, attr, value|
|
666
|
-
value = options[:tokenizer].call(value) if value.kind_of?(String)
|
667
|
-
if value.nil? or value.size < option_value.begin
|
668
|
-
record.errors.add(attr, :too_short, :default => custom_message || options[:too_short], :count => option_value.begin)
|
669
|
-
elsif value.size > option_value.end
|
670
|
-
record.errors.add(attr, :too_long, :default => custom_message || options[:too_long], :count => option_value.end)
|
671
|
-
end
|
672
|
-
end
|
673
|
-
when :is, :minimum, :maximum
|
674
|
-
raise ArgumentError, ":#{option} must be a nonnegative Integer" unless option_value.is_a?(Integer) and option_value >= 0
|
675
|
-
|
676
|
-
# Declare different validations per option.
|
677
|
-
validity_checks = { :is => "==", :minimum => ">=", :maximum => "<=" }
|
678
|
-
|
679
|
-
validates_each(attrs, options) do |record, attr, value|
|
680
|
-
value = options[:tokenizer].call(value) if value.kind_of?(String)
|
681
|
-
unless !value.nil? and value.size.method(validity_checks[option])[option_value]
|
682
|
-
record.errors.add(attr, key, :default => custom_message, :count => option_value)
|
683
|
-
end
|
684
|
-
end
|
685
|
-
end
|
686
|
-
end
|
687
|
-
|
688
|
-
alias_method :validates_size_of, :validates_length_of
|
689
|
-
|
690
|
-
|
691
|
-
# Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user
|
692
|
-
# can be named "davidhh".
|
693
|
-
#
|
694
|
-
# class Person < ActiveRecord::Base
|
695
|
-
# validates_uniqueness_of :user_name, :scope => :account_id
|
696
|
-
# end
|
697
|
-
#
|
698
|
-
# It can also validate whether the value of the specified attributes are unique based on multiple scope parameters. For example,
|
699
|
-
# making sure that a teacher can only be on the schedule once per semester for a particular class.
|
700
|
-
#
|
701
|
-
# class TeacherSchedule < ActiveRecord::Base
|
702
|
-
# validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
|
703
|
-
# end
|
704
|
-
#
|
705
|
-
# When the record is created, a check is performed to make sure that no record exists in the database with the given value for the specified
|
706
|
-
# attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.
|
707
|
-
#
|
708
|
-
# Configuration options:
|
709
|
-
# * <tt>:message</tt> - Specifies a custom error message (default is: "has already been taken").
|
710
|
-
# * <tt>:scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint.
|
711
|
-
# * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (+true+ by default).
|
712
|
-
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
|
713
|
-
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
|
714
|
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
715
|
-
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
|
716
|
-
# method, proc or string should return or evaluate to a true or false value.
|
717
|
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
718
|
-
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
|
719
|
-
# method, proc or string should return or evaluate to a true or false value.
|
720
|
-
#
|
721
|
-
# === Concurrency and integrity
|
722
|
-
#
|
723
|
-
# Using this validation method in conjunction with ActiveRecord::Base#save
|
724
|
-
# does not guarantee the absence of duplicate record insertions, because
|
725
|
-
# uniqueness checks on the application level are inherently prone to race
|
726
|
-
# conditions. For example, suppose that two users try to post a Comment at
|
727
|
-
# the same time, and a Comment's title must be unique. At the database-level,
|
728
|
-
# the actions performed by these users could be interleaved in the following manner:
|
729
|
-
#
|
730
|
-
# User 1 | User 2
|
731
|
-
# ------------------------------------+--------------------------------------
|
732
|
-
# # User 1 checks whether there's |
|
733
|
-
# # already a comment with the title |
|
734
|
-
# # 'My Post'. This is not the case. |
|
735
|
-
# SELECT * FROM comments |
|
736
|
-
# WHERE title = 'My Post' |
|
737
|
-
# |
|
738
|
-
# | # User 2 does the same thing and also
|
739
|
-
# | # infers that his title is unique.
|
740
|
-
# | SELECT * FROM comments
|
741
|
-
# | WHERE title = 'My Post'
|
742
|
-
# |
|
743
|
-
# # User 1 inserts his comment. |
|
744
|
-
# INSERT INTO comments |
|
745
|
-
# (title, content) VALUES |
|
746
|
-
# ('My Post', 'hi!') |
|
747
|
-
# |
|
748
|
-
# | # User 2 does the same thing.
|
749
|
-
# | INSERT INTO comments
|
750
|
-
# | (title, content) VALUES
|
751
|
-
# | ('My Post', 'hello!')
|
752
|
-
# |
|
753
|
-
# | # ^^^^^^
|
754
|
-
# | # Boom! We now have a duplicate
|
755
|
-
# | # title!
|
756
|
-
#
|
757
|
-
# This could even happen if you use transactions with the 'serializable'
|
758
|
-
# isolation level. There are several ways to get around this problem:
|
759
|
-
# - By locking the database table before validating, and unlocking it after
|
760
|
-
# saving. However, table locking is very expensive, and thus not
|
761
|
-
# recommended.
|
762
|
-
# - By locking a lock file before validating, and unlocking it after saving.
|
763
|
-
# This does not work if you've scaled your Rails application across
|
764
|
-
# multiple web servers (because they cannot share lock files, or cannot
|
765
|
-
# do that efficiently), and thus not recommended.
|
766
|
-
# - Creating a unique index on the field, by using
|
767
|
-
# ActiveRecord::ConnectionAdapters::SchemaStatements#add_index. In the
|
768
|
-
# rare case that a race condition occurs, the database will guarantee
|
769
|
-
# the field's uniqueness.
|
770
|
-
#
|
771
|
-
# When the database catches such a duplicate insertion,
|
772
|
-
# ActiveRecord::Base#save will raise an ActiveRecord::StatementInvalid
|
773
|
-
# exception. You can either choose to let this error propagate (which
|
774
|
-
# will result in the default Rails exception page being shown), or you
|
775
|
-
# can catch it and restart the transaction (e.g. by telling the user
|
776
|
-
# that the title already exists, and asking him to re-enter the title).
|
777
|
-
# This technique is also known as optimistic concurrency control:
|
778
|
-
# http://en.wikipedia.org/wiki/Optimistic_concurrency_control
|
779
|
-
#
|
780
|
-
# Active Record currently provides no way to distinguish unique
|
781
|
-
# index constraint errors from other types of database errors, so you
|
782
|
-
# will have to parse the (database-specific) exception message to detect
|
783
|
-
# such a case.
|
784
|
-
def validates_uniqueness_of(*attr_names)
|
785
|
-
configuration = { :case_sensitive => true }
|
786
|
-
configuration.update(attr_names.extract_options!)
|
787
|
-
|
788
|
-
validates_each(attr_names,configuration) do |record, attr_name, value|
|
789
|
-
# The check for an existing value should be run from a class that
|
790
|
-
# isn't abstract. This means working down from the current class
|
791
|
-
# (self), to the first non-abstract class. Since classes don't know
|
792
|
-
# their subclasses, we have to build the hierarchy between self and
|
793
|
-
# the record's class.
|
794
|
-
class_hierarchy = [record.class]
|
795
|
-
while class_hierarchy.first != self
|
796
|
-
class_hierarchy.insert(0, class_hierarchy.first.superclass)
|
797
|
-
end
|
798
|
-
|
799
|
-
# Now we can work our way down the tree to the first non-abstract
|
800
|
-
# class (which has a database table to query from).
|
801
|
-
finder_class = class_hierarchy.detect { |klass| !klass.abstract_class? }
|
802
|
-
|
803
|
-
column = finder_class.columns_hash[attr_name.to_s]
|
804
|
-
|
805
|
-
if value.nil?
|
806
|
-
comparison_operator = "IS ?"
|
807
|
-
elsif column.text?
|
808
|
-
comparison_operator = "#{connection.case_sensitive_equality_operator} ?"
|
809
|
-
value = column.limit ? value.to_s.mb_chars[0, column.limit] : value.to_s
|
810
|
-
else
|
811
|
-
comparison_operator = "= ?"
|
812
|
-
end
|
813
|
-
|
814
|
-
sql_attribute = "#{record.class.quoted_table_name}.#{connection.quote_column_name(attr_name)}"
|
815
|
-
|
816
|
-
if value.nil? || (configuration[:case_sensitive] || !column.text?)
|
817
|
-
condition_sql = "#{sql_attribute} #{comparison_operator}"
|
818
|
-
condition_params = [value]
|
819
|
-
else
|
820
|
-
condition_sql = "LOWER(#{sql_attribute}) #{comparison_operator}"
|
821
|
-
condition_params = [value.mb_chars.downcase]
|
822
|
-
end
|
823
|
-
|
824
|
-
if scope = configuration[:scope]
|
825
|
-
Array(scope).map do |scope_item|
|
826
|
-
scope_value = record.send(scope_item)
|
827
|
-
condition_sql << " AND " << attribute_condition("#{record.class.quoted_table_name}.#{connection.quote_column_name(scope_item)}", scope_value)
|
828
|
-
condition_params << scope_value
|
829
|
-
end
|
830
|
-
end
|
831
|
-
|
832
|
-
unless record.new_record?
|
833
|
-
condition_sql << " AND #{record.class.quoted_table_name}.#{record.class.primary_key} <> ?"
|
834
|
-
condition_params << record.send(:id)
|
835
|
-
end
|
836
|
-
|
837
|
-
finder_class.with_exclusive_scope do
|
838
|
-
if finder_class.exists?([condition_sql, *condition_params])
|
839
|
-
record.errors.add(attr_name, :taken, :default => configuration[:message], :value => value)
|
840
|
-
end
|
841
|
-
end
|
842
|
-
end
|
843
|
-
end
|
844
|
-
|
845
|
-
|
846
|
-
# Validates whether the value of the specified attribute is of the correct form by matching it against the regular expression
|
847
|
-
# provided.
|
848
|
-
#
|
849
|
-
# class Person < ActiveRecord::Base
|
850
|
-
# validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
|
851
|
-
# end
|
852
|
-
#
|
853
|
-
# Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the string, <tt>^</tt> and <tt>$</tt> match the start/end of a line.
|
854
|
-
#
|
855
|
-
# A regular expression must be provided or else an exception will be raised.
|
856
|
-
#
|
857
|
-
# Configuration options:
|
858
|
-
# * <tt>:message</tt> - A custom error message (default is: "is invalid").
|
859
|
-
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
|
860
|
-
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
|
861
|
-
# * <tt>:with</tt> - The regular expression used to validate the format with (note: must be supplied!).
|
862
|
-
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
|
863
|
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
864
|
-
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
|
865
|
-
# method, proc or string should return or evaluate to a true or false value.
|
866
|
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
867
|
-
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
|
868
|
-
# method, proc or string should return or evaluate to a true or false value.
|
869
|
-
def validates_format_of(*attr_names)
|
870
|
-
configuration = { :on => :save, :with => nil }
|
871
|
-
configuration.update(attr_names.extract_options!)
|
872
|
-
|
873
|
-
raise(ArgumentError, "A regular expression must be supplied as the :with option of the configuration hash") unless configuration[:with].is_a?(Regexp)
|
874
|
-
|
875
|
-
validates_each(attr_names, configuration) do |record, attr_name, value|
|
876
|
-
unless value.to_s =~ configuration[:with]
|
877
|
-
record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value)
|
878
|
-
end
|
879
|
-
end
|
880
|
-
end
|
881
|
-
|
882
|
-
# Validates whether the value of the specified attribute is available in a particular enumerable object.
|
883
|
-
#
|
884
|
-
# class Person < ActiveRecord::Base
|
885
|
-
# validates_inclusion_of :gender, :in => %w( m f )
|
886
|
-
# validates_inclusion_of :age, :in => 0..99
|
887
|
-
# validates_inclusion_of :format, :in => %w( jpg gif png ), :message => "extension %{value} is not included in the list"
|
888
|
-
# end
|
889
|
-
#
|
890
|
-
# Configuration options:
|
891
|
-
# * <tt>:in</tt> - An enumerable object of available items.
|
892
|
-
# * <tt>:message</tt> - Specifies a custom error message (default is: "is not included in the list").
|
893
|
-
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
|
894
|
-
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
|
895
|
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
896
|
-
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
|
897
|
-
# method, proc or string should return or evaluate to a true or false value.
|
898
|
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
899
|
-
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
|
900
|
-
# method, proc or string should return or evaluate to a true or false value.
|
901
|
-
def validates_inclusion_of(*attr_names)
|
902
|
-
configuration = { :on => :save }
|
903
|
-
configuration.update(attr_names.extract_options!)
|
904
|
-
|
905
|
-
enum = configuration[:in] || configuration[:within]
|
906
|
-
|
907
|
-
raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?(:include?)
|
908
|
-
|
909
|
-
validates_each(attr_names, configuration) do |record, attr_name, value|
|
910
|
-
unless enum.include?(value)
|
911
|
-
record.errors.add(attr_name, :inclusion, :default => configuration[:message], :value => value)
|
912
|
-
end
|
913
|
-
end
|
914
|
-
end
|
915
|
-
|
916
|
-
# Validates that the value of the specified attribute is not in a particular enumerable object.
|
917
|
-
#
|
918
|
-
# class Person < ActiveRecord::Base
|
919
|
-
# validates_exclusion_of :username, :in => %w( admin superuser ), :message => "You don't belong here"
|
920
|
-
# validates_exclusion_of :age, :in => 30..60, :message => "This site is only for under 30 and over 60"
|
921
|
-
# validates_exclusion_of :format, :in => %w( mov avi ), :message => "extension %{value} is not allowed"
|
922
|
-
# end
|
923
|
-
#
|
924
|
-
# Configuration options:
|
925
|
-
# * <tt>:in</tt> - An enumerable object of items that the value shouldn't be part of.
|
926
|
-
# * <tt>:message</tt> - Specifies a custom error message (default is: "is reserved").
|
927
|
-
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
|
928
|
-
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
|
929
|
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
930
|
-
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
|
931
|
-
# method, proc or string should return or evaluate to a true or false value.
|
932
|
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
933
|
-
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
|
934
|
-
# method, proc or string should return or evaluate to a true or false value.
|
935
|
-
def validates_exclusion_of(*attr_names)
|
936
|
-
configuration = { :on => :save }
|
937
|
-
configuration.update(attr_names.extract_options!)
|
938
|
-
|
939
|
-
enum = configuration[:in] || configuration[:within]
|
940
|
-
|
941
|
-
raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?(:include?)
|
942
|
-
|
943
|
-
validates_each(attr_names, configuration) do |record, attr_name, value|
|
944
|
-
if enum.include?(value)
|
945
|
-
record.errors.add(attr_name, :exclusion, :default => configuration[:message], :value => value)
|
946
|
-
end
|
947
|
-
end
|
948
|
-
end
|
949
|
-
|
950
|
-
# Validates whether the associated object or objects are all valid themselves. Works with any kind of association.
|
951
|
-
#
|
952
|
-
# class Book < ActiveRecord::Base
|
953
|
-
# has_many :pages
|
954
|
-
# belongs_to :library
|
955
|
-
#
|
956
|
-
# validates_associated :pages, :library
|
957
|
-
# end
|
958
|
-
#
|
959
|
-
# Warning: If, after the above definition, you then wrote:
|
960
|
-
#
|
961
|
-
# class Page < ActiveRecord::Base
|
962
|
-
# belongs_to :book
|
963
|
-
#
|
964
|
-
# validates_associated :book
|
965
|
-
# end
|
966
|
-
#
|
967
|
-
# this would specify a circular dependency and cause infinite recursion.
|
968
|
-
#
|
969
|
-
# NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association
|
970
|
-
# is both present and guaranteed to be valid, you also need to use +validates_presence_of+.
|
971
|
-
#
|
972
|
-
# Configuration options:
|
973
|
-
# * <tt>:message</tt> - A custom error message (default is: "is invalid")
|
974
|
-
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
|
975
|
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
976
|
-
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
|
977
|
-
# method, proc or string should return or evaluate to a true or false value.
|
978
|
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
979
|
-
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
|
980
|
-
# method, proc or string should return or evaluate to a true or false value.
|
981
|
-
def validates_associated(*attr_names)
|
982
|
-
configuration = { :on => :save }
|
983
|
-
configuration.update(attr_names.extract_options!)
|
984
|
-
|
985
|
-
validates_each(attr_names, configuration) do |record, attr_name, value|
|
986
|
-
unless (value.is_a?(Array) ? value : [value]).collect { |r| r.nil? || r.valid? }.all?
|
987
|
-
record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value)
|
988
|
-
end
|
989
|
-
end
|
990
|
-
end
|
991
|
-
|
992
|
-
# Validates whether the value of the specified attribute is numeric by trying to convert it to
|
993
|
-
# a float with Kernel.Float (if <tt>only_integer</tt> is false) or applying it to the regular expression
|
994
|
-
# <tt>/\A[\+\-]?\d+\Z/</tt> (if <tt>only_integer</tt> is set to true).
|
995
|
-
#
|
996
|
-
# class Person < ActiveRecord::Base
|
997
|
-
# validates_numericality_of :value, :on => :create
|
998
|
-
# end
|
999
|
-
#
|
1000
|
-
# Configuration options:
|
1001
|
-
# * <tt>:message</tt> - A custom error message (default is: "is not a number").
|
1002
|
-
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
|
1003
|
-
# * <tt>:only_integer</tt> - Specifies whether the value has to be an integer, e.g. an integral value (default is +false+).
|
1004
|
-
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is +false+). Notice that for fixnum and float columns empty strings are converted to +nil+.
|
1005
|
-
# * <tt>:greater_than</tt> - Specifies the value must be greater than the supplied value.
|
1006
|
-
# * <tt>:greater_than_or_equal_to</tt> - Specifies the value must be greater than or equal the supplied value.
|
1007
|
-
# * <tt>:equal_to</tt> - Specifies the value must be equal to the supplied value.
|
1008
|
-
# * <tt>:less_than</tt> - Specifies the value must be less than the supplied value.
|
1009
|
-
# * <tt>:less_than_or_equal_to</tt> - Specifies the value must be less than or equal the supplied value.
|
1010
|
-
# * <tt>:odd</tt> - Specifies the value must be an odd number.
|
1011
|
-
# * <tt>:even</tt> - Specifies the value must be an even number.
|
1012
|
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
1013
|
-
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
|
1014
|
-
# method, proc or string should return or evaluate to a true or false value.
|
1015
|
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
1016
|
-
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
|
1017
|
-
# method, proc or string should return or evaluate to a true or false value.
|
1018
|
-
def validates_numericality_of(*attr_names)
|
1019
|
-
configuration = { :on => :save, :only_integer => false, :allow_nil => false }
|
1020
|
-
configuration.update(attr_names.extract_options!)
|
1021
|
-
|
1022
|
-
|
1023
|
-
numericality_options = ALL_NUMERICALITY_CHECKS.keys & configuration.keys
|
1024
|
-
|
1025
|
-
(numericality_options - [ :odd, :even ]).each do |option|
|
1026
|
-
raise ArgumentError, ":#{option} must be a number" unless configuration[option].is_a?(Numeric)
|
1027
|
-
end
|
1028
|
-
|
1029
|
-
validates_each(attr_names,configuration) do |record, attr_name, value|
|
1030
|
-
raw_value = record.send("#{attr_name}_before_type_cast") || value
|
1031
|
-
|
1032
|
-
next if configuration[:allow_nil] and raw_value.nil?
|
1033
|
-
|
1034
|
-
if configuration[:only_integer]
|
1035
|
-
unless raw_value.to_s =~ /\A[+-]?\d+\Z/
|
1036
|
-
record.errors.add(attr_name, :not_a_number, :value => raw_value, :default => configuration[:message])
|
1037
|
-
next
|
1038
|
-
end
|
1039
|
-
raw_value = raw_value.to_i
|
1040
|
-
else
|
1041
|
-
begin
|
1042
|
-
raw_value = Kernel.Float(raw_value)
|
1043
|
-
rescue ArgumentError, TypeError
|
1044
|
-
record.errors.add(attr_name, :not_a_number, :value => raw_value, :default => configuration[:message])
|
1045
|
-
next
|
1046
|
-
end
|
1047
|
-
end
|
1048
|
-
|
1049
|
-
numericality_options.each do |option|
|
1050
|
-
case option
|
1051
|
-
when :odd, :even
|
1052
|
-
unless raw_value.to_i.method(ALL_NUMERICALITY_CHECKS[option])[]
|
1053
|
-
record.errors.add(attr_name, option, :value => raw_value, :default => configuration[:message])
|
1054
|
-
end
|
1055
|
-
else
|
1056
|
-
record.errors.add(attr_name, option, :default => configuration[:message], :value => raw_value, :count => configuration[option]) unless raw_value.method(ALL_NUMERICALITY_CHECKS[option])[configuration[option]]
|
1057
|
-
end
|
1058
|
-
end
|
1059
|
-
end
|
1060
|
-
end
|
1061
|
-
|
1062
|
-
# Creates an object just like Base.create but calls save! instead of save
|
33
|
+
# Creates an object just like Base.create but calls <tt>save!</tt> instead of +save+
|
1063
34
|
# so an exception is raised if the record is invalid.
|
1064
|
-
def create!(attributes = nil, &block)
|
35
|
+
def create!(attributes = nil, options = {}, &block)
|
1065
36
|
if attributes.is_a?(Array)
|
1066
|
-
attributes.collect { |attr| create!(attr, &block) }
|
37
|
+
attributes.collect { |attr| create!(attr, options, &block) }
|
1067
38
|
else
|
1068
|
-
object = new(attributes)
|
39
|
+
object = new(attributes, options)
|
1069
40
|
yield(object) if block_given?
|
1070
41
|
object.save!
|
1071
42
|
object
|
1072
43
|
end
|
1073
44
|
end
|
1074
|
-
|
1075
|
-
private
|
1076
|
-
def validation_method(on)
|
1077
|
-
case on
|
1078
|
-
when :save then :validate
|
1079
|
-
when :create then :validate_on_create
|
1080
|
-
when :update then :validate_on_update
|
1081
|
-
end
|
1082
|
-
end
|
1083
45
|
end
|
1084
46
|
|
1085
|
-
# The validation process on save can be skipped by passing false
|
47
|
+
# The validation process on save can be skipped by passing <tt>:validate => false</tt>. The regular Base#save method is
|
1086
48
|
# replaced with this when the validations module is mixed in, which it is by default.
|
1087
|
-
def
|
1088
|
-
|
1089
|
-
save_without_validation
|
1090
|
-
else
|
1091
|
-
false
|
1092
|
-
end
|
49
|
+
def save(options={})
|
50
|
+
perform_validations(options) ? super : false
|
1093
51
|
end
|
1094
52
|
|
1095
|
-
# Attempts to save the record just like Base#save but will raise a RecordInvalid exception instead of returning false
|
53
|
+
# Attempts to save the record just like Base#save but will raise a +RecordInvalid+ exception instead of returning false
|
1096
54
|
# if the record is not valid.
|
1097
|
-
def
|
1098
|
-
|
1099
|
-
save_without_validation!
|
1100
|
-
else
|
1101
|
-
raise RecordInvalid.new(self)
|
1102
|
-
end
|
55
|
+
def save!(options={})
|
56
|
+
perform_validations(options) ? super : raise(RecordInvalid.new(self))
|
1103
57
|
end
|
1104
58
|
|
1105
|
-
# Runs
|
1106
|
-
|
1107
|
-
|
1108
|
-
|
1109
|
-
|
1110
|
-
|
1111
|
-
|
1112
|
-
|
1113
|
-
|
1114
|
-
|
1115
|
-
|
1116
|
-
|
1117
|
-
validate_on_update
|
1118
|
-
end
|
1119
|
-
|
1120
|
-
errors.empty?
|
59
|
+
# Runs all the validations within the specified context. Returns true if no errors are found,
|
60
|
+
# false otherwise.
|
61
|
+
#
|
62
|
+
# If the argument is false (default is +nil+), the context is set to <tt>:create</tt> if
|
63
|
+
# <tt>new_record?</tt> is true, and to <tt>:update</tt> if it is not.
|
64
|
+
#
|
65
|
+
# Validations with no <tt>:on</tt> option will run no matter the context. Validations with
|
66
|
+
# some <tt>:on</tt> option will only run in the specified context.
|
67
|
+
def valid?(context = nil)
|
68
|
+
context ||= (new_record? ? :create : :update)
|
69
|
+
output = super(context)
|
70
|
+
errors.empty? && output
|
1121
71
|
end
|
1122
72
|
|
1123
|
-
|
1124
|
-
def invalid?
|
1125
|
-
!valid?
|
1126
|
-
end
|
73
|
+
protected
|
1127
74
|
|
1128
|
-
|
1129
|
-
|
1130
|
-
|
75
|
+
def perform_validations(options={})
|
76
|
+
perform_validation = options[:validate] != false
|
77
|
+
perform_validation ? valid?(options[:context]) : true
|
1131
78
|
end
|
1132
|
-
|
1133
|
-
protected
|
1134
|
-
# Overwrite this method for validation checks on all saves and use <tt>Errors.add(field, msg)</tt> for invalid attributes.
|
1135
|
-
def validate
|
1136
|
-
end
|
1137
|
-
|
1138
|
-
# Overwrite this method for validation checks used only on creation.
|
1139
|
-
def validate_on_create
|
1140
|
-
end
|
1141
|
-
|
1142
|
-
# Overwrite this method for validation checks used only on updates.
|
1143
|
-
def validate_on_update
|
1144
|
-
end
|
1145
79
|
end
|
1146
80
|
end
|
81
|
+
|
82
|
+
require "active_record/validations/associated"
|
83
|
+
require "active_record/validations/uniqueness"
|