activerecord 1.0.0 → 2.0.0
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.
- data/CHANGELOG +4928 -3
- data/README +45 -46
- data/RUNNING_UNIT_TESTS +8 -11
- data/Rakefile +247 -0
- data/install.rb +8 -38
- data/lib/active_record/aggregations.rb +64 -49
- data/lib/active_record/associations/association_collection.rb +217 -47
- data/lib/active_record/associations/association_proxy.rb +159 -0
- data/lib/active_record/associations/belongs_to_association.rb +56 -0
- data/lib/active_record/associations/belongs_to_polymorphic_association.rb +50 -0
- data/lib/active_record/associations/has_and_belongs_to_many_association.rb +155 -37
- data/lib/active_record/associations/has_many_association.rb +145 -75
- data/lib/active_record/associations/has_many_through_association.rb +283 -0
- data/lib/active_record/associations/has_one_association.rb +96 -0
- data/lib/active_record/associations.rb +1537 -304
- data/lib/active_record/attribute_methods.rb +328 -0
- data/lib/active_record/base.rb +2001 -588
- data/lib/active_record/calculations.rb +269 -0
- data/lib/active_record/callbacks.rb +169 -165
- data/lib/active_record/connection_adapters/abstract/connection_specification.rb +308 -0
- data/lib/active_record/connection_adapters/abstract/database_statements.rb +171 -0
- data/lib/active_record/connection_adapters/abstract/query_cache.rb +87 -0
- data/lib/active_record/connection_adapters/abstract/quoting.rb +69 -0
- data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +472 -0
- data/lib/active_record/connection_adapters/abstract/schema_statements.rb +306 -0
- data/lib/active_record/connection_adapters/abstract_adapter.rb +125 -279
- data/lib/active_record/connection_adapters/mysql_adapter.rb +442 -77
- data/lib/active_record/connection_adapters/postgresql_adapter.rb +805 -135
- data/lib/active_record/connection_adapters/sqlite3_adapter.rb +34 -0
- data/lib/active_record/connection_adapters/sqlite_adapter.rb +353 -69
- data/lib/active_record/fixtures.rb +946 -100
- data/lib/active_record/locking/optimistic.rb +144 -0
- data/lib/active_record/locking/pessimistic.rb +77 -0
- data/lib/active_record/migration.rb +417 -0
- data/lib/active_record/observer.rb +142 -32
- data/lib/active_record/query_cache.rb +23 -0
- data/lib/active_record/reflection.rb +163 -70
- data/lib/active_record/schema.rb +58 -0
- data/lib/active_record/schema_dumper.rb +171 -0
- data/lib/active_record/serialization.rb +98 -0
- data/lib/active_record/serializers/json_serializer.rb +71 -0
- data/lib/active_record/serializers/xml_serializer.rb +315 -0
- data/lib/active_record/timestamp.rb +41 -0
- data/lib/active_record/transactions.rb +87 -57
- data/lib/active_record/validations.rb +909 -122
- data/lib/active_record/vendor/db2.rb +362 -0
- data/lib/active_record/vendor/mysql.rb +126 -29
- data/lib/active_record/version.rb +9 -0
- data/lib/active_record.rb +35 -7
- data/lib/activerecord.rb +1 -0
- data/test/aaa_create_tables_test.rb +72 -0
- data/test/abstract_unit.rb +73 -5
- data/test/active_schema_test_mysql.rb +43 -0
- data/test/adapter_test.rb +105 -0
- data/test/adapter_test_sqlserver.rb +95 -0
- data/test/aggregations_test.rb +110 -16
- data/test/all.sh +2 -2
- data/test/ar_schema_test.rb +33 -0
- data/test/association_inheritance_reload.rb +14 -0
- data/test/associations/ar_joins_test.rb +0 -0
- data/test/associations/callbacks_test.rb +147 -0
- data/test/associations/cascaded_eager_loading_test.rb +110 -0
- data/test/associations/eager_singularization_test.rb +145 -0
- data/test/associations/eager_test.rb +442 -0
- data/test/associations/extension_test.rb +47 -0
- data/test/associations/inner_join_association_test.rb +88 -0
- data/test/associations/join_model_test.rb +553 -0
- data/test/associations_test.rb +1930 -267
- data/test/attribute_methods_test.rb +146 -0
- data/test/base_test.rb +1316 -84
- data/test/binary_test.rb +32 -0
- data/test/calculations_test.rb +251 -0
- data/test/callbacks_test.rb +400 -0
- data/test/class_inheritable_attributes_test.rb +3 -4
- data/test/column_alias_test.rb +17 -0
- data/test/connection_test_firebird.rb +8 -0
- data/test/connection_test_mysql.rb +30 -0
- data/test/connections/native_db2/connection.rb +25 -0
- data/test/connections/native_firebird/connection.rb +26 -0
- data/test/connections/native_frontbase/connection.rb +27 -0
- data/test/connections/native_mysql/connection.rb +21 -18
- data/test/connections/native_openbase/connection.rb +21 -0
- data/test/connections/native_oracle/connection.rb +27 -0
- data/test/connections/native_postgresql/connection.rb +17 -18
- data/test/connections/native_sqlite/connection.rb +17 -16
- data/test/connections/native_sqlite3/connection.rb +25 -0
- data/test/connections/native_sqlite3/in_memory_connection.rb +18 -0
- data/test/connections/native_sybase/connection.rb +23 -0
- data/test/copy_table_test_sqlite.rb +69 -0
- data/test/datatype_test_postgresql.rb +203 -0
- data/test/date_time_test.rb +37 -0
- data/test/default_test_firebird.rb +16 -0
- data/test/defaults_test.rb +67 -0
- data/test/deprecated_finder_test.rb +30 -0
- data/test/finder_test.rb +607 -32
- data/test/fixtures/accounts.yml +28 -0
- 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.rb +107 -0
- data/test/fixtures/author_favorites.yml +4 -0
- data/test/fixtures/authors.yml +7 -0
- data/test/fixtures/bad_fixtures/attr_with_numeric_first_char +1 -0
- data/test/fixtures/bad_fixtures/attr_with_spaces +1 -0
- data/test/fixtures/bad_fixtures/blank_line +3 -0
- data/test/fixtures/bad_fixtures/duplicate_attributes +3 -0
- data/test/fixtures/bad_fixtures/missing_value +1 -0
- data/test/fixtures/binaries.yml +132 -0
- data/test/fixtures/binary.rb +2 -0
- data/test/fixtures/book.rb +4 -0
- data/test/fixtures/books.yml +7 -0
- data/test/fixtures/categories/special_categories.yml +9 -0
- data/test/fixtures/categories/subsubdir/arbitrary_filename.yml +4 -0
- data/test/fixtures/categories.yml +14 -0
- data/test/fixtures/categories_ordered.yml +7 -0
- data/test/fixtures/categories_posts.yml +23 -0
- data/test/fixtures/categorization.rb +5 -0
- data/test/fixtures/categorizations.yml +17 -0
- data/test/fixtures/category.rb +26 -0
- data/test/fixtures/citation.rb +6 -0
- data/test/fixtures/comment.rb +23 -0
- data/test/fixtures/comments.yml +59 -0
- data/test/fixtures/companies.yml +55 -0
- data/test/fixtures/company.rb +81 -4
- data/test/fixtures/company_in_module.rb +32 -6
- data/test/fixtures/computer.rb +4 -0
- data/test/fixtures/computers.yml +4 -0
- data/test/fixtures/contact.rb +16 -0
- data/test/fixtures/courses.yml +7 -0
- data/test/fixtures/customer.rb +28 -3
- data/test/fixtures/customers.yml +17 -0
- data/test/fixtures/db_definitions/db2.drop.sql +33 -0
- data/test/fixtures/db_definitions/db2.sql +235 -0
- data/test/fixtures/db_definitions/db22.drop.sql +2 -0
- data/test/fixtures/db_definitions/db22.sql +5 -0
- data/test/fixtures/db_definitions/firebird.drop.sql +65 -0
- data/test/fixtures/db_definitions/firebird.sql +310 -0
- data/test/fixtures/db_definitions/firebird2.drop.sql +2 -0
- data/test/fixtures/db_definitions/firebird2.sql +6 -0
- data/test/fixtures/db_definitions/frontbase.drop.sql +33 -0
- data/test/fixtures/db_definitions/frontbase.sql +273 -0
- data/test/fixtures/db_definitions/frontbase2.drop.sql +1 -0
- data/test/fixtures/db_definitions/frontbase2.sql +4 -0
- data/test/fixtures/db_definitions/openbase.drop.sql +2 -0
- data/test/fixtures/db_definitions/openbase.sql +318 -0
- data/test/fixtures/db_definitions/openbase2.drop.sql +2 -0
- data/test/fixtures/db_definitions/openbase2.sql +7 -0
- data/test/fixtures/db_definitions/oracle.drop.sql +67 -0
- data/test/fixtures/db_definitions/oracle.sql +330 -0
- data/test/fixtures/db_definitions/oracle2.drop.sql +2 -0
- data/test/fixtures/db_definitions/oracle2.sql +6 -0
- data/test/fixtures/db_definitions/postgresql.drop.sql +44 -0
- data/test/fixtures/db_definitions/postgresql.sql +217 -38
- data/test/fixtures/db_definitions/postgresql2.drop.sql +2 -0
- data/test/fixtures/db_definitions/postgresql2.sql +2 -2
- data/test/fixtures/db_definitions/schema.rb +354 -0
- data/test/fixtures/db_definitions/schema2.rb +11 -0
- data/test/fixtures/db_definitions/sqlite.drop.sql +33 -0
- data/test/fixtures/db_definitions/sqlite.sql +139 -5
- data/test/fixtures/db_definitions/sqlite2.drop.sql +2 -0
- data/test/fixtures/db_definitions/sqlite2.sql +1 -0
- data/test/fixtures/db_definitions/sybase.drop.sql +35 -0
- data/test/fixtures/db_definitions/sybase.sql +222 -0
- data/test/fixtures/db_definitions/sybase2.drop.sql +4 -0
- data/test/fixtures/db_definitions/sybase2.sql +5 -0
- data/test/fixtures/developer.rb +70 -6
- data/test/fixtures/developers.yml +21 -0
- data/test/fixtures/developers_projects/david_action_controller +2 -1
- data/test/fixtures/developers_projects/david_active_record +2 -1
- data/test/fixtures/developers_projects.yml +17 -0
- data/test/fixtures/edge.rb +5 -0
- data/test/fixtures/edges.yml +6 -0
- data/test/fixtures/entrants.yml +14 -0
- data/test/fixtures/example.log +1 -0
- data/test/fixtures/fk_test_has_fk.yml +3 -0
- data/test/fixtures/fk_test_has_pk.yml +2 -0
- data/test/fixtures/flowers.jpg +0 -0
- data/test/fixtures/funny_jokes.yml +10 -0
- data/test/fixtures/item.rb +7 -0
- data/test/fixtures/items.yml +4 -0
- data/test/fixtures/joke.rb +3 -0
- data/test/fixtures/keyboard.rb +3 -0
- data/test/fixtures/legacy_thing.rb +3 -0
- data/test/fixtures/legacy_things.yml +3 -0
- data/test/fixtures/matey.rb +4 -0
- data/test/fixtures/mateys.yml +4 -0
- data/test/fixtures/migrations/1_people_have_last_names.rb +9 -0
- data/test/fixtures/migrations/2_we_need_reminders.rb +12 -0
- data/test/fixtures/migrations/3_innocent_jointable.rb +12 -0
- data/test/fixtures/migrations_with_decimal/1_give_me_big_numbers.rb +15 -0
- data/test/fixtures/migrations_with_duplicate/1_people_have_last_names.rb +9 -0
- data/test/fixtures/migrations_with_duplicate/2_we_need_reminders.rb +12 -0
- data/test/fixtures/migrations_with_duplicate/3_foo.rb +7 -0
- data/test/fixtures/migrations_with_duplicate/3_innocent_jointable.rb +12 -0
- data/test/fixtures/migrations_with_missing_versions/1000_people_have_middle_names.rb +9 -0
- data/test/fixtures/migrations_with_missing_versions/1_people_have_last_names.rb +9 -0
- data/test/fixtures/migrations_with_missing_versions/3_we_need_reminders.rb +12 -0
- data/test/fixtures/migrations_with_missing_versions/4_innocent_jointable.rb +12 -0
- data/test/fixtures/minimalistic.rb +2 -0
- data/test/fixtures/minimalistics.yml +2 -0
- data/test/fixtures/mixed_case_monkey.rb +3 -0
- data/test/fixtures/mixed_case_monkeys.yml +6 -0
- data/test/fixtures/mixins.yml +29 -0
- data/test/fixtures/movies.yml +7 -0
- data/test/fixtures/naked/csv/accounts.csv +1 -0
- data/test/fixtures/naked/yml/accounts.yml +1 -0
- data/test/fixtures/naked/yml/companies.yml +1 -0
- data/test/fixtures/naked/yml/courses.yml +1 -0
- data/test/fixtures/order.rb +4 -0
- data/test/fixtures/parrot.rb +13 -0
- data/test/fixtures/parrots.yml +27 -0
- data/test/fixtures/parrots_pirates.yml +7 -0
- data/test/fixtures/people.yml +3 -0
- data/test/fixtures/person.rb +4 -0
- data/test/fixtures/pirate.rb +5 -0
- data/test/fixtures/pirates.yml +9 -0
- data/test/fixtures/post.rb +59 -0
- data/test/fixtures/posts.yml +48 -0
- data/test/fixtures/project.rb +27 -2
- data/test/fixtures/projects.yml +7 -0
- data/test/fixtures/reader.rb +4 -0
- data/test/fixtures/readers.yml +4 -0
- data/test/fixtures/reply.rb +18 -2
- data/test/fixtures/reserved_words/distinct.yml +5 -0
- data/test/fixtures/reserved_words/distincts_selects.yml +11 -0
- data/test/fixtures/reserved_words/group.yml +14 -0
- data/test/fixtures/reserved_words/select.yml +8 -0
- data/test/fixtures/reserved_words/values.yml +7 -0
- data/test/fixtures/ship.rb +3 -0
- data/test/fixtures/ships.yml +5 -0
- data/test/fixtures/subject.rb +4 -0
- data/test/fixtures/subscriber.rb +4 -3
- data/test/fixtures/tag.rb +7 -0
- data/test/fixtures/tagging.rb +10 -0
- data/test/fixtures/taggings.yml +25 -0
- data/test/fixtures/tags.yml +7 -0
- data/test/fixtures/task.rb +3 -0
- data/test/fixtures/tasks.yml +7 -0
- data/test/fixtures/topic.rb +20 -3
- data/test/fixtures/topics.yml +22 -0
- data/test/fixtures/treasure.rb +4 -0
- data/test/fixtures/treasures.yml +10 -0
- data/test/fixtures/vertex.rb +9 -0
- data/test/fixtures/vertices.yml +4 -0
- data/test/fixtures_test.rb +574 -8
- data/test/inheritance_test.rb +113 -27
- data/test/json_serialization_test.rb +180 -0
- data/test/lifecycle_test.rb +56 -29
- data/test/locking_test.rb +273 -0
- data/test/method_scoping_test.rb +416 -0
- data/test/migration_test.rb +933 -0
- data/test/migration_test_firebird.rb +124 -0
- data/test/mixin_test.rb +95 -0
- data/test/modules_test.rb +23 -10
- data/test/multiple_db_test.rb +17 -3
- data/test/pk_test.rb +59 -15
- data/test/query_cache_test.rb +104 -0
- data/test/readonly_test.rb +107 -0
- data/test/reflection_test.rb +124 -27
- data/test/reserved_word_test_mysql.rb +177 -0
- data/test/schema_authorization_test_postgresql.rb +75 -0
- data/test/schema_dumper_test.rb +131 -0
- data/test/schema_test_postgresql.rb +64 -0
- data/test/serialization_test.rb +47 -0
- data/test/synonym_test_oracle.rb +17 -0
- data/test/table_name_test_sqlserver.rb +23 -0
- data/test/threaded_connections_test.rb +48 -0
- data/test/transactions_test.rb +227 -29
- data/test/unconnected_test.rb +14 -6
- data/test/validations_test.rb +1293 -32
- data/test/xml_serialization_test.rb +202 -0
- metadata +347 -143
- data/dev-utils/eval_debugger.rb +0 -9
- data/examples/associations.rb +0 -87
- data/examples/shared_setup.rb +0 -15
- data/examples/validation.rb +0 -88
- data/lib/active_record/deprecated_associations.rb +0 -70
- data/lib/active_record/support/class_attribute_accessors.rb +0 -43
- data/lib/active_record/support/class_inheritable_attributes.rb +0 -37
- data/lib/active_record/support/clean_logger.rb +0 -10
- data/lib/active_record/support/inflector.rb +0 -70
- data/lib/active_record/vendor/simple.rb +0 -702
- data/lib/active_record/wrappers/yaml_wrapper.rb +0 -15
- data/lib/active_record/wrappings.rb +0 -59
- data/rakefile +0 -122
- data/test/deprecated_associations_test.rb +0 -336
- data/test/fixtures/accounts/signals37 +0 -3
- data/test/fixtures/accounts/unknown +0 -2
- data/test/fixtures/companies/first_client +0 -6
- data/test/fixtures/companies/first_firm +0 -4
- data/test/fixtures/companies/second_client +0 -6
- data/test/fixtures/courses/java +0 -2
- data/test/fixtures/courses/ruby +0 -2
- data/test/fixtures/customers/david +0 -6
- data/test/fixtures/db_definitions/mysql.sql +0 -96
- data/test/fixtures/db_definitions/mysql2.sql +0 -4
- data/test/fixtures/developers/david +0 -2
- data/test/fixtures/developers/jamis +0 -2
- data/test/fixtures/entrants/first +0 -3
- data/test/fixtures/entrants/second +0 -3
- data/test/fixtures/entrants/third +0 -3
- data/test/fixtures/fixture_database.sqlite +0 -0
- data/test/fixtures/fixture_database_2.sqlite +0 -0
- data/test/fixtures/movies/first +0 -2
- data/test/fixtures/movies/second +0 -2
- data/test/fixtures/projects/action_controller +0 -2
- data/test/fixtures/projects/active_record +0 -2
- data/test/fixtures/topics/first +0 -9
- data/test/fixtures/topics/second +0 -8
- data/test/inflector_test.rb +0 -104
- data/test/thread_safety_test.rb +0 -33
@@ -1,5 +1,235 @@
|
|
1
1
|
module ActiveRecord
|
2
|
-
#
|
2
|
+
# Raised by save! and create! when the record is invalid. Use the
|
3
|
+
# record method to retrieve the record which did not validate.
|
4
|
+
# begin
|
5
|
+
# complex_operation_that_calls_save!_internally
|
6
|
+
# rescue ActiveRecord::RecordInvalid => invalid
|
7
|
+
# puts invalid.record.errors
|
8
|
+
# end
|
9
|
+
class RecordInvalid < ActiveRecordError #:nodoc:
|
10
|
+
attr_reader :record
|
11
|
+
def initialize(record)
|
12
|
+
@record = record
|
13
|
+
super("Validation failed: #{@record.errors.full_messages.join(", ")}")
|
14
|
+
end
|
15
|
+
end
|
16
|
+
|
17
|
+
# Active Record validation is reported to and from this object, which is used by Base#save to
|
18
|
+
# determine whether the object is in a valid state to be saved. See usage example in Validations.
|
19
|
+
class Errors
|
20
|
+
include Enumerable
|
21
|
+
|
22
|
+
def initialize(base) # :nodoc:
|
23
|
+
@base, @errors = base, {}
|
24
|
+
end
|
25
|
+
|
26
|
+
@@default_error_messages = {
|
27
|
+
:inclusion => "is not included in the list",
|
28
|
+
:exclusion => "is reserved",
|
29
|
+
:invalid => "is invalid",
|
30
|
+
:confirmation => "doesn't match confirmation",
|
31
|
+
:accepted => "must be accepted",
|
32
|
+
:empty => "can't be empty",
|
33
|
+
:blank => "can't be blank",
|
34
|
+
:too_long => "is too long (maximum is %d characters)",
|
35
|
+
:too_short => "is too short (minimum is %d characters)",
|
36
|
+
:wrong_length => "is the wrong length (should be %d characters)",
|
37
|
+
:taken => "has already been taken",
|
38
|
+
:not_a_number => "is not a number",
|
39
|
+
:greater_than => "must be greater than %d",
|
40
|
+
:greater_than_or_equal_to => "must be greater than or equal to %d",
|
41
|
+
:equal_to => "must be equal to %d",
|
42
|
+
:less_than => "must be less than %d",
|
43
|
+
:less_than_or_equal_to => "must be less than or equal to %d",
|
44
|
+
:odd => "must be odd",
|
45
|
+
:even => "must be even"
|
46
|
+
}
|
47
|
+
|
48
|
+
# Holds a hash with all the default error messages that can be replaced by your own copy or localizations.
|
49
|
+
cattr_accessor :default_error_messages
|
50
|
+
|
51
|
+
|
52
|
+
# Adds an error to the base object instead of any particular attribute. This is used
|
53
|
+
# to report errors that don't tie to any specific attribute, but rather to the object
|
54
|
+
# as a whole. These error messages don't get prepended with any field name when iterating
|
55
|
+
# with each_full, so they should be complete sentences.
|
56
|
+
def add_to_base(msg)
|
57
|
+
add(:base, msg)
|
58
|
+
end
|
59
|
+
|
60
|
+
# Adds an error message (+msg+) to the +attribute+, which will be returned on a call to <tt>on(attribute)</tt>
|
61
|
+
# for the same attribute and ensure that this error object returns false when asked if <tt>empty?</tt>. More than one
|
62
|
+
# error can be added to the same +attribute+ in which case an array will be returned on a call to <tt>on(attribute)</tt>.
|
63
|
+
# If no +msg+ is supplied, "invalid" is assumed.
|
64
|
+
def add(attribute, msg = @@default_error_messages[:invalid])
|
65
|
+
@errors[attribute.to_s] = [] if @errors[attribute.to_s].nil?
|
66
|
+
@errors[attribute.to_s] << msg
|
67
|
+
end
|
68
|
+
|
69
|
+
# Will add an error message to each of the attributes in +attributes+ that is empty.
|
70
|
+
def add_on_empty(attributes, msg = @@default_error_messages[:empty])
|
71
|
+
for attr in [attributes].flatten
|
72
|
+
value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
|
73
|
+
is_empty = value.respond_to?("empty?") ? value.empty? : false
|
74
|
+
add(attr, msg) unless !value.nil? && !is_empty
|
75
|
+
end
|
76
|
+
end
|
77
|
+
|
78
|
+
# Will add an error message to each of the attributes in +attributes+ that is blank (using Object#blank?).
|
79
|
+
def add_on_blank(attributes, msg = @@default_error_messages[:blank])
|
80
|
+
for attr in [attributes].flatten
|
81
|
+
value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
|
82
|
+
add(attr, msg) if value.blank?
|
83
|
+
end
|
84
|
+
end
|
85
|
+
|
86
|
+
# Returns true if the specified +attribute+ has errors associated with it.
|
87
|
+
#
|
88
|
+
# class Company < ActiveRecord::Base
|
89
|
+
# validates_presence_of :name, :address, :email
|
90
|
+
# validates_length_of :name, :in => 5..30
|
91
|
+
# end
|
92
|
+
#
|
93
|
+
# company = Company.create(:address => '123 First St.')
|
94
|
+
# company.errors.invalid?(:name) # => true
|
95
|
+
# company.errors.invalid?(:address) # => false
|
96
|
+
def invalid?(attribute)
|
97
|
+
!@errors[attribute.to_s].nil?
|
98
|
+
end
|
99
|
+
|
100
|
+
# Returns nil, if no errors are associated with the specified +attribute+.
|
101
|
+
# Returns the error message, if one error is associated with the specified +attribute+.
|
102
|
+
# Returns an array of error messages, if more than one error is associated with the specified +attribute+.
|
103
|
+
#
|
104
|
+
# class Company < ActiveRecord::Base
|
105
|
+
# validates_presence_of :name, :address, :email
|
106
|
+
# validates_length_of :name, :in => 5..30
|
107
|
+
# end
|
108
|
+
#
|
109
|
+
# company = Company.create(:address => '123 First St.')
|
110
|
+
# company.errors.on(:name) # => ["is too short (minimum is 5 characters)", "can't be blank"]
|
111
|
+
# company.errors.on(:email) # => "can't be blank"
|
112
|
+
# company.errors.on(:address) # => nil
|
113
|
+
def on(attribute)
|
114
|
+
errors = @errors[attribute.to_s]
|
115
|
+
return nil if errors.nil?
|
116
|
+
errors.size == 1 ? errors.first : errors
|
117
|
+
end
|
118
|
+
|
119
|
+
alias :[] :on
|
120
|
+
|
121
|
+
# Returns errors assigned to the base object through add_to_base according to the normal rules of on(attribute).
|
122
|
+
def on_base
|
123
|
+
on(:base)
|
124
|
+
end
|
125
|
+
|
126
|
+
# Yields each attribute and associated message per error added.
|
127
|
+
#
|
128
|
+
# class Company < ActiveRecord::Base
|
129
|
+
# validates_presence_of :name, :address, :email
|
130
|
+
# validates_length_of :name, :in => 5..30
|
131
|
+
# end
|
132
|
+
#
|
133
|
+
# company = Company.create(:address => '123 First St.')
|
134
|
+
# company.errors.each{|attr,msg| puts "#{attr} - #{msg}" } # =>
|
135
|
+
# name - is too short (minimum is 5 characters)
|
136
|
+
# name - can't be blank
|
137
|
+
# address - can't be blank
|
138
|
+
def each
|
139
|
+
@errors.each_key { |attr| @errors[attr].each { |msg| yield attr, msg } }
|
140
|
+
end
|
141
|
+
|
142
|
+
# Yields each full error message added. So Person.errors.add("first_name", "can't be empty") will be returned
|
143
|
+
# through iteration as "First name can't be empty".
|
144
|
+
#
|
145
|
+
# class Company < ActiveRecord::Base
|
146
|
+
# validates_presence_of :name, :address, :email
|
147
|
+
# validates_length_of :name, :in => 5..30
|
148
|
+
# end
|
149
|
+
#
|
150
|
+
# company = Company.create(:address => '123 First St.')
|
151
|
+
# company.errors.each_full{|msg| puts msg } # =>
|
152
|
+
# Name is too short (minimum is 5 characters)
|
153
|
+
# Name can't be blank
|
154
|
+
# Address can't be blank
|
155
|
+
def each_full
|
156
|
+
full_messages.each { |msg| yield msg }
|
157
|
+
end
|
158
|
+
|
159
|
+
# Returns all the full error messages in an array.
|
160
|
+
#
|
161
|
+
# class Company < ActiveRecord::Base
|
162
|
+
# validates_presence_of :name, :address, :email
|
163
|
+
# validates_length_of :name, :in => 5..30
|
164
|
+
# end
|
165
|
+
#
|
166
|
+
# company = Company.create(:address => '123 First St.')
|
167
|
+
# company.errors.full_messages # =>
|
168
|
+
# ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Address can't be blank"]
|
169
|
+
def full_messages
|
170
|
+
full_messages = []
|
171
|
+
|
172
|
+
@errors.each_key do |attr|
|
173
|
+
@errors[attr].each do |msg|
|
174
|
+
next if msg.nil?
|
175
|
+
|
176
|
+
if attr == "base"
|
177
|
+
full_messages << msg
|
178
|
+
else
|
179
|
+
full_messages << @base.class.human_attribute_name(attr) + " " + msg
|
180
|
+
end
|
181
|
+
end
|
182
|
+
end
|
183
|
+
full_messages
|
184
|
+
end
|
185
|
+
|
186
|
+
# Returns true if no errors have been added.
|
187
|
+
def empty?
|
188
|
+
@errors.empty?
|
189
|
+
end
|
190
|
+
|
191
|
+
# Removes all errors that have been added.
|
192
|
+
def clear
|
193
|
+
@errors = {}
|
194
|
+
end
|
195
|
+
|
196
|
+
# Returns the total number of errors added. Two errors added to the same attribute will be counted as such.
|
197
|
+
def size
|
198
|
+
@errors.values.inject(0) { |error_count, attribute| error_count + attribute.size }
|
199
|
+
end
|
200
|
+
|
201
|
+
alias_method :count, :size
|
202
|
+
alias_method :length, :size
|
203
|
+
|
204
|
+
# Return an XML representation of this error object.
|
205
|
+
#
|
206
|
+
# class Company < ActiveRecord::Base
|
207
|
+
# validates_presence_of :name, :address, :email
|
208
|
+
# validates_length_of :name, :in => 5..30
|
209
|
+
# end
|
210
|
+
#
|
211
|
+
# company = Company.create(:address => '123 First St.')
|
212
|
+
# company.errors.to_xml # =>
|
213
|
+
# <?xml version="1.0" encoding="UTF-8"?>
|
214
|
+
# <errors>
|
215
|
+
# <error>Name is too short (minimum is 5 characters)</error>
|
216
|
+
# <error>Name can't be blank</error>
|
217
|
+
# <error>Address can't be blank</error>
|
218
|
+
# </errors>
|
219
|
+
def to_xml(options={})
|
220
|
+
options[:root] ||= "errors"
|
221
|
+
options[:indent] ||= 2
|
222
|
+
options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
|
223
|
+
|
224
|
+
options[:builder].instruct! unless options.delete(:skip_instruct)
|
225
|
+
options[:builder].errors do |e|
|
226
|
+
full_messages.each { |msg| e.error(msg) }
|
227
|
+
end
|
228
|
+
end
|
229
|
+
end
|
230
|
+
|
231
|
+
|
232
|
+
# Active Records implement validation by overwriting Base#validate (or the variations, +validate_on_create+ and
|
3
233
|
# +validate_on_update+). Each of these methods can inspect the state of the object, which usually means ensuring
|
4
234
|
# that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).
|
5
235
|
#
|
@@ -19,68 +249,706 @@ module ActiveRecord
|
|
19
249
|
# end
|
20
250
|
#
|
21
251
|
# def validate_on_update
|
22
|
-
# errors.add_to_base("No changes have
|
252
|
+
# errors.add_to_base("No changes have occurred") if unchanged_attributes?
|
23
253
|
# end
|
24
254
|
# end
|
25
255
|
#
|
26
256
|
# person = Person.new("first_name" => "David", "phone_number" => "what?")
|
27
257
|
# person.save # => false (and doesn't do the save)
|
28
258
|
# person.errors.empty? # => false
|
29
|
-
# person.count
|
259
|
+
# person.errors.count # => 2
|
30
260
|
# person.errors.on "last_name" # => "can't be empty"
|
31
261
|
# person.errors.on "phone_number" # => "has invalid format"
|
32
|
-
# person.each_full { |msg| puts msg }
|
262
|
+
# person.errors.each_full { |msg| puts msg }
|
263
|
+
# # => "Last name can't be empty\n" +
|
33
264
|
# "Phone number has invalid format"
|
34
265
|
#
|
35
266
|
# person.attributes = { "last_name" => "Heinemeier", "phone_number" => "555-555" }
|
36
267
|
# person.save # => true (and person is now saved in the database)
|
37
268
|
#
|
38
269
|
# An +Errors+ object is automatically created for every Active Record.
|
270
|
+
#
|
271
|
+
# Please do have a look at ActiveRecord::Validations::ClassMethods for a higher level of validations.
|
39
272
|
module Validations
|
40
|
-
|
41
|
-
super
|
273
|
+
VALIDATIONS = %w( validate validate_on_create validate_on_update )
|
42
274
|
|
275
|
+
def self.included(base) # :nodoc:
|
276
|
+
base.extend ClassMethods
|
43
277
|
base.class_eval do
|
44
|
-
|
45
|
-
|
278
|
+
alias_method_chain :save, :validation
|
279
|
+
alias_method_chain :save!, :validation
|
280
|
+
alias_method_chain :update_attribute, :validation_skipping
|
281
|
+
end
|
282
|
+
end
|
283
|
+
|
284
|
+
# All of the following validations are defined in the class scope of the model that you're interested in validating.
|
285
|
+
# They offer a more declarative way of specifying when the model is valid and when it is not. It is recommended to use
|
286
|
+
# these over the low-level calls to validate and validate_on_create when possible.
|
287
|
+
module ClassMethods
|
288
|
+
DEFAULT_VALIDATION_OPTIONS = {
|
289
|
+
:on => :save,
|
290
|
+
:allow_nil => false,
|
291
|
+
:allow_blank => false,
|
292
|
+
:message => nil
|
293
|
+
}.freeze
|
294
|
+
|
295
|
+
ALL_RANGE_OPTIONS = [ :is, :within, :in, :minimum, :maximum ].freeze
|
296
|
+
ALL_NUMERICALITY_CHECKS = { :greater_than => '>', :greater_than_or_equal_to => '>=',
|
297
|
+
:equal_to => '==', :less_than => '<', :less_than_or_equal_to => '<=',
|
298
|
+
:odd => 'odd?', :even => 'even?' }.freeze
|
299
|
+
|
300
|
+
|
301
|
+
def validate(*methods, &block)
|
302
|
+
methods << block if block_given?
|
303
|
+
write_inheritable_set(:validate, methods)
|
304
|
+
end
|
305
|
+
|
306
|
+
def validate_on_create(*methods, &block)
|
307
|
+
methods << block if block_given?
|
308
|
+
write_inheritable_set(:validate_on_create, methods)
|
309
|
+
end
|
310
|
+
|
311
|
+
def validate_on_update(*methods, &block)
|
312
|
+
methods << block if block_given?
|
313
|
+
write_inheritable_set(:validate_on_update, methods)
|
314
|
+
end
|
315
|
+
|
316
|
+
def condition_block?(condition)
|
317
|
+
condition.respond_to?("call") && (condition.arity == 1 || condition.arity == -1)
|
318
|
+
end
|
319
|
+
|
320
|
+
# Determine from the given condition (whether a block, procedure, method or string)
|
321
|
+
# whether or not to validate the record. See #validates_each.
|
322
|
+
def evaluate_condition(condition, record)
|
323
|
+
case condition
|
324
|
+
when Symbol; record.send(condition)
|
325
|
+
when String; eval(condition, record.send(:binding))
|
326
|
+
else
|
327
|
+
if condition_block?(condition)
|
328
|
+
condition.call(record)
|
329
|
+
else
|
330
|
+
raise(
|
331
|
+
ActiveRecordError,
|
332
|
+
"Validations need to be either a symbol, string (to be eval'ed), proc/method, or " +
|
333
|
+
"class implementing a static validation method"
|
334
|
+
)
|
335
|
+
end
|
336
|
+
end
|
337
|
+
end
|
338
|
+
|
339
|
+
# Validates each attribute against a block.
|
340
|
+
#
|
341
|
+
# class Person < ActiveRecord::Base
|
342
|
+
# validates_each :first_name, :last_name do |record, attr, value|
|
343
|
+
# record.errors.add attr, 'starts with z.' if value[0] == ?z
|
344
|
+
# end
|
345
|
+
# end
|
346
|
+
#
|
347
|
+
# Options:
|
348
|
+
# * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
|
349
|
+
# * <tt>allow_nil</tt> - Skip validation if attribute is nil.
|
350
|
+
# * <tt>allow_blank</tt> - Skip validation if attribute is blank.
|
351
|
+
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
352
|
+
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
|
353
|
+
# method, proc or string should return or evaluate to a true or false value.
|
354
|
+
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
355
|
+
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
|
356
|
+
# method, proc or string should return or evaluate to a true or false value.
|
357
|
+
def validates_each(*attrs)
|
358
|
+
options = attrs.extract_options!.symbolize_keys
|
359
|
+
attrs = attrs.flatten
|
360
|
+
|
361
|
+
# Declare the validation.
|
362
|
+
send(validation_method(options[:on] || :save)) do |record|
|
363
|
+
# Don't validate when there is an :if condition and that condition is false or there is an :unless condition and that condition is true
|
364
|
+
unless (options[:if] && !evaluate_condition(options[:if], record)) || (options[:unless] && evaluate_condition(options[:unless], record))
|
365
|
+
attrs.each do |attr|
|
366
|
+
value = record.send(attr)
|
367
|
+
next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
|
368
|
+
yield record, attr, value
|
369
|
+
end
|
370
|
+
end
|
371
|
+
end
|
372
|
+
end
|
373
|
+
|
374
|
+
# Encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example:
|
375
|
+
#
|
376
|
+
# Model:
|
377
|
+
# class Person < ActiveRecord::Base
|
378
|
+
# validates_confirmation_of :user_name, :password
|
379
|
+
# validates_confirmation_of :email_address, :message => "should match confirmation"
|
380
|
+
# end
|
381
|
+
#
|
382
|
+
# View:
|
383
|
+
# <%= password_field "person", "password" %>
|
384
|
+
# <%= password_field "person", "password_confirmation" %>
|
385
|
+
#
|
386
|
+
# The added +password_confirmation+ attribute is virtual; it exists only as an in-memory attribute for validating the password.
|
387
|
+
# To achieve this, the validation adds acccessors to the model for the confirmation attribute. NOTE: This check is performed
|
388
|
+
# only if +password_confirmation+ is not nil, and by default only on save. To require confirmation, make sure to add a presence
|
389
|
+
# check for the confirmation attribute:
|
390
|
+
#
|
391
|
+
# validates_presence_of :password_confirmation, :if => :password_changed?
|
392
|
+
#
|
393
|
+
# Configuration options:
|
394
|
+
# * <tt>message</tt> - A custom error message (default is: "doesn't match confirmation")
|
395
|
+
# * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
|
396
|
+
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
397
|
+
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
|
398
|
+
# method, proc or string should return or evaluate to a true or false value.
|
399
|
+
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
400
|
+
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
|
401
|
+
# method, proc or string should return or evaluate to a true or false value.
|
402
|
+
def validates_confirmation_of(*attr_names)
|
403
|
+
configuration = { :message => ActiveRecord::Errors.default_error_messages[:confirmation], :on => :save }
|
404
|
+
configuration.update(attr_names.extract_options!)
|
405
|
+
|
406
|
+
attr_accessor *(attr_names.map { |n| "#{n}_confirmation" })
|
407
|
+
|
408
|
+
validates_each(attr_names, configuration) do |record, attr_name, value|
|
409
|
+
record.errors.add(attr_name, configuration[:message]) unless record.send("#{attr_name}_confirmation").nil? or value == record.send("#{attr_name}_confirmation")
|
410
|
+
end
|
411
|
+
end
|
412
|
+
|
413
|
+
# Encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example:
|
414
|
+
#
|
415
|
+
# class Person < ActiveRecord::Base
|
416
|
+
# validates_acceptance_of :terms_of_service
|
417
|
+
# validates_acceptance_of :eula, :message => "must be abided"
|
418
|
+
# end
|
419
|
+
#
|
420
|
+
# If the database column does not exist, the terms_of_service attribute is entirely virtual. This check is
|
421
|
+
# performed only if terms_of_service is not nil and by default on save.
|
422
|
+
#
|
423
|
+
# Configuration options:
|
424
|
+
# * <tt>message</tt> - A custom error message (default is: "must be accepted")
|
425
|
+
# * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
|
426
|
+
# * <tt>allow_nil</tt> - Skip validation if attribute is nil. (default is true)
|
427
|
+
# * <tt>accept</tt> - Specifies value that is considered accepted. The default value is a string "1", which
|
428
|
+
# makes it easy to relate to an HTML checkbox.
|
429
|
+
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
430
|
+
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
|
431
|
+
# method, proc or string should return or evaluate to a true or false value.
|
432
|
+
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
433
|
+
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
|
434
|
+
# method, proc or string should return or evaluate to a true or false value.
|
435
|
+
def validates_acceptance_of(*attr_names)
|
436
|
+
configuration = { :message => ActiveRecord::Errors.default_error_messages[:accepted], :on => :save, :allow_nil => true, :accept => "1" }
|
437
|
+
configuration.update(attr_names.extract_options!)
|
438
|
+
|
439
|
+
attr_accessor *attr_names.reject { |name| column_names.include? name.to_s }
|
440
|
+
|
441
|
+
validates_each(attr_names,configuration) do |record, attr_name, value|
|
442
|
+
record.errors.add(attr_name, configuration[:message]) unless value == configuration[:accept]
|
443
|
+
end
|
444
|
+
end
|
445
|
+
|
446
|
+
# Validates that the specified attributes are not blank (as defined by Object#blank?). Happens by default on save. Example:
|
447
|
+
#
|
448
|
+
# class Person < ActiveRecord::Base
|
449
|
+
# validates_presence_of :first_name
|
450
|
+
# end
|
451
|
+
#
|
452
|
+
# The first_name attribute must be in the object and it cannot be blank.
|
453
|
+
#
|
454
|
+
# If you want to validate the presence of a boolean field (where the real values are true and false),
|
455
|
+
# you will want to use validates_inclusion_of :field_name, :in => [true, false]
|
456
|
+
# This is due to the way Object#blank? handles boolean values. false.blank? # => true
|
457
|
+
#
|
458
|
+
# Configuration options:
|
459
|
+
# * <tt>message</tt> - A custom error message (default is: "can't be blank")
|
460
|
+
# * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
|
461
|
+
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
462
|
+
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
|
463
|
+
# method, proc or string should return or evaluate to a true or false value.
|
464
|
+
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
465
|
+
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
|
466
|
+
# method, proc or string should return or evaluate to a true or false value.
|
467
|
+
#
|
468
|
+
# === Warning
|
469
|
+
# Validate the presence of the foreign key, not the instance variable itself.
|
470
|
+
# Do this:
|
471
|
+
# validates_presence_of :invoice_id
|
472
|
+
#
|
473
|
+
# Not this:
|
474
|
+
# validates_presence_of :invoice
|
475
|
+
#
|
476
|
+
# If you validate the presence of the associated object, you will get
|
477
|
+
# failures on saves when both the parent object and the child object are
|
478
|
+
# new.
|
479
|
+
def validates_presence_of(*attr_names)
|
480
|
+
configuration = { :message => ActiveRecord::Errors.default_error_messages[:blank], :on => :save }
|
481
|
+
configuration.update(attr_names.extract_options!)
|
482
|
+
|
483
|
+
# can't use validates_each here, because it cannot cope with nonexistent attributes,
|
484
|
+
# while errors.add_on_empty can
|
485
|
+
send(validation_method(configuration[:on])) do |record|
|
486
|
+
unless (configuration[:if] && !evaluate_condition(configuration[:if], record)) || (configuration[:unless] && evaluate_condition(configuration[:unless], record))
|
487
|
+
record.errors.add_on_blank(attr_names, configuration[:message])
|
488
|
+
end
|
489
|
+
end
|
490
|
+
end
|
491
|
+
|
492
|
+
# Validates that the specified attribute matches the length restrictions supplied. Only one option can be used at a time:
|
493
|
+
#
|
494
|
+
# class Person < ActiveRecord::Base
|
495
|
+
# validates_length_of :first_name, :maximum=>30
|
496
|
+
# validates_length_of :last_name, :maximum=>30, :message=>"less than %d if you don't mind"
|
497
|
+
# validates_length_of :fax, :in => 7..32, :allow_nil => true
|
498
|
+
# validates_length_of :phone, :in => 7..32, :allow_blank => true
|
499
|
+
# validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
|
500
|
+
# validates_length_of :fav_bra_size, :minimum=>1, :too_short=>"please enter at least %d character"
|
501
|
+
# validates_length_of :smurf_leader, :is=>4, :message=>"papa is spelled with %d characters... don't play me."
|
502
|
+
# end
|
503
|
+
#
|
504
|
+
# Configuration options:
|
505
|
+
# * <tt>minimum</tt> - The minimum size of the attribute
|
506
|
+
# * <tt>maximum</tt> - The maximum size of the attribute
|
507
|
+
# * <tt>is</tt> - The exact size of the attribute
|
508
|
+
# * <tt>within</tt> - A range specifying the minimum and maximum size of the attribute
|
509
|
+
# * <tt>in</tt> - A synonym(or alias) for :within
|
510
|
+
# * <tt>allow_nil</tt> - Attribute may be nil; skip validation.
|
511
|
+
# * <tt>allow_blank</tt> - Attribute may be blank; skip validation.
|
512
|
+
#
|
513
|
+
# * <tt>too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is %d characters)")
|
514
|
+
# * <tt>too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is %d characters)")
|
515
|
+
# * <tt>wrong_length</tt> - The error message if using the :is method and the attribute is the wrong size (default is: "is the wrong length (should be %d characters)")
|
516
|
+
# * <tt>message</tt> - The error message to use for a :minimum, :maximum, or :is violation. An alias of the appropriate too_long/too_short/wrong_length message
|
517
|
+
# * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
|
518
|
+
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
519
|
+
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
|
520
|
+
# method, proc or string should return or evaluate to a true or false value.
|
521
|
+
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
522
|
+
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
|
523
|
+
# method, proc or string should return or evaluate to a true or false value.
|
524
|
+
def validates_length_of(*attrs)
|
525
|
+
# Merge given options with defaults.
|
526
|
+
options = {
|
527
|
+
:too_long => ActiveRecord::Errors.default_error_messages[:too_long],
|
528
|
+
:too_short => ActiveRecord::Errors.default_error_messages[:too_short],
|
529
|
+
:wrong_length => ActiveRecord::Errors.default_error_messages[:wrong_length]
|
530
|
+
}.merge(DEFAULT_VALIDATION_OPTIONS)
|
531
|
+
options.update(attrs.extract_options!.symbolize_keys)
|
532
|
+
|
533
|
+
# Ensure that one and only one range option is specified.
|
534
|
+
range_options = ALL_RANGE_OPTIONS & options.keys
|
535
|
+
case range_options.size
|
536
|
+
when 0
|
537
|
+
raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.'
|
538
|
+
when 1
|
539
|
+
# Valid number of options; do nothing.
|
540
|
+
else
|
541
|
+
raise ArgumentError, 'Too many range options specified. Choose only one.'
|
542
|
+
end
|
543
|
+
|
544
|
+
# Get range option and value.
|
545
|
+
option = range_options.first
|
546
|
+
option_value = options[range_options.first]
|
547
|
+
|
548
|
+
case option
|
549
|
+
when :within, :in
|
550
|
+
raise ArgumentError, ":#{option} must be a Range" unless option_value.is_a?(Range)
|
551
|
+
|
552
|
+
too_short = options[:too_short] % option_value.begin
|
553
|
+
too_long = options[:too_long] % option_value.end
|
554
|
+
|
555
|
+
validates_each(attrs, options) do |record, attr, value|
|
556
|
+
if value.nil? or value.split(//).size < option_value.begin
|
557
|
+
record.errors.add(attr, too_short)
|
558
|
+
elsif value.split(//).size > option_value.end
|
559
|
+
record.errors.add(attr, too_long)
|
560
|
+
end
|
561
|
+
end
|
562
|
+
when :is, :minimum, :maximum
|
563
|
+
raise ArgumentError, ":#{option} must be a nonnegative Integer" unless option_value.is_a?(Integer) and option_value >= 0
|
564
|
+
|
565
|
+
# Declare different validations per option.
|
566
|
+
validity_checks = { :is => "==", :minimum => ">=", :maximum => "<=" }
|
567
|
+
message_options = { :is => :wrong_length, :minimum => :too_short, :maximum => :too_long }
|
568
|
+
|
569
|
+
message = (options[:message] || options[message_options[option]]) % option_value
|
570
|
+
|
571
|
+
validates_each(attrs, options) do |record, attr, value|
|
572
|
+
if value.kind_of?(String)
|
573
|
+
record.errors.add(attr, message) unless !value.nil? and value.split(//).size.method(validity_checks[option])[option_value]
|
574
|
+
else
|
575
|
+
record.errors.add(attr, message) unless !value.nil? and value.size.method(validity_checks[option])[option_value]
|
576
|
+
end
|
577
|
+
end
|
578
|
+
end
|
579
|
+
end
|
46
580
|
|
47
|
-
|
48
|
-
|
581
|
+
alias_method :validates_size_of, :validates_length_of
|
582
|
+
|
583
|
+
|
584
|
+
# Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user
|
585
|
+
# can be named "davidhh".
|
586
|
+
#
|
587
|
+
# class Person < ActiveRecord::Base
|
588
|
+
# validates_uniqueness_of :user_name, :scope => :account_id
|
589
|
+
# end
|
590
|
+
#
|
591
|
+
# It can also validate whether the value of the specified attributes are unique based on multiple scope parameters. For example,
|
592
|
+
# making sure that a teacher can only be on the schedule once per semester for a particular class.
|
593
|
+
#
|
594
|
+
# class TeacherSchedule < ActiveRecord::Base
|
595
|
+
# validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
|
596
|
+
# end
|
597
|
+
#
|
598
|
+
# 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
|
599
|
+
# attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.
|
600
|
+
#
|
601
|
+
# Because this check is performed outside the database there is still a chance that duplicate values
|
602
|
+
# will be inserted in two parallel transactions. To guarantee against this you should create a
|
603
|
+
# unique index on the field. See +create_index+ for more information.
|
604
|
+
#
|
605
|
+
# Configuration options:
|
606
|
+
# * <tt>message</tt> - Specifies a custom error message (default is: "has already been taken")
|
607
|
+
# * <tt>scope</tt> - One or more columns by which to limit the scope of the uniquness constraint.
|
608
|
+
# * <tt>case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (true by default).
|
609
|
+
# * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
|
610
|
+
# * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
|
611
|
+
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
612
|
+
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
|
613
|
+
# method, proc or string should return or evaluate to a true or false value.
|
614
|
+
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
615
|
+
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
|
616
|
+
# method, proc or string should return or evaluate to a true or false value.
|
617
|
+
def validates_uniqueness_of(*attr_names)
|
618
|
+
configuration = { :message => ActiveRecord::Errors.default_error_messages[:taken], :case_sensitive => true }
|
619
|
+
configuration.update(attr_names.extract_options!)
|
620
|
+
|
621
|
+
validates_each(attr_names,configuration) do |record, attr_name, value|
|
622
|
+
if value.nil? || (configuration[:case_sensitive] || !columns_hash[attr_name.to_s].text?)
|
623
|
+
condition_sql = "#{record.class.table_name}.#{attr_name} #{attribute_condition(value)}"
|
624
|
+
condition_params = [value]
|
625
|
+
else
|
626
|
+
condition_sql = "LOWER(#{record.class.table_name}.#{attr_name}) #{attribute_condition(value)}"
|
627
|
+
condition_params = [value.downcase]
|
628
|
+
end
|
629
|
+
|
630
|
+
if scope = configuration[:scope]
|
631
|
+
Array(scope).map do |scope_item|
|
632
|
+
scope_value = record.send(scope_item)
|
633
|
+
condition_sql << " AND #{record.class.table_name}.#{scope_item} #{attribute_condition(scope_value)}"
|
634
|
+
condition_params << scope_value
|
635
|
+
end
|
636
|
+
end
|
637
|
+
|
638
|
+
unless record.new_record?
|
639
|
+
condition_sql << " AND #{record.class.table_name}.#{record.class.primary_key} <> ?"
|
640
|
+
condition_params << record.send(:id)
|
641
|
+
end
|
642
|
+
|
643
|
+
# The check for an existing value should be run from a class that
|
644
|
+
# isn't abstract. This means working down from the current class
|
645
|
+
# (self), to the first non-abstract class. Since classes don't know
|
646
|
+
# their subclasses, we have to build the hierarchy between self and
|
647
|
+
# the record's class.
|
648
|
+
class_hierarchy = [record.class]
|
649
|
+
while class_hierarchy.first != self
|
650
|
+
class_hierarchy.insert(0, class_hierarchy.first.superclass)
|
651
|
+
end
|
652
|
+
|
653
|
+
# Now we can work our way down the tree to the first non-abstract
|
654
|
+
# class (which has a database table to query from).
|
655
|
+
finder_class = class_hierarchy.detect { |klass| !klass.abstract_class? }
|
656
|
+
|
657
|
+
if finder_class.find(:first, :conditions => [condition_sql, *condition_params])
|
658
|
+
record.errors.add(attr_name, configuration[:message])
|
659
|
+
end
|
660
|
+
end
|
49
661
|
end
|
662
|
+
|
663
|
+
|
664
|
+
# Validates whether the value of the specified attribute is of the correct form by matching it against the regular expression
|
665
|
+
# provided.
|
666
|
+
#
|
667
|
+
# class Person < ActiveRecord::Base
|
668
|
+
# validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
|
669
|
+
# end
|
670
|
+
#
|
671
|
+
# Note: use \A and \Z to match the start and end of the string, ^ and $ match the start/end of a line.
|
672
|
+
#
|
673
|
+
# A regular expression must be provided or else an exception will be raised.
|
674
|
+
#
|
675
|
+
# Configuration options:
|
676
|
+
# * <tt>message</tt> - A custom error message (default is: "is invalid")
|
677
|
+
# * <tt>with</tt> - The regular expression used to validate the format with (note: must be supplied!)
|
678
|
+
# * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
|
679
|
+
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
680
|
+
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
|
681
|
+
# method, proc or string should return or evaluate to a true or false value.
|
682
|
+
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
683
|
+
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
|
684
|
+
# method, proc or string should return or evaluate to a true or false value.
|
685
|
+
def validates_format_of(*attr_names)
|
686
|
+
configuration = { :message => ActiveRecord::Errors.default_error_messages[:invalid], :on => :save, :with => nil }
|
687
|
+
configuration.update(attr_names.extract_options!)
|
688
|
+
|
689
|
+
raise(ArgumentError, "A regular expression must be supplied as the :with option of the configuration hash") unless configuration[:with].is_a?(Regexp)
|
690
|
+
|
691
|
+
validates_each(attr_names, configuration) do |record, attr_name, value|
|
692
|
+
record.errors.add(attr_name, configuration[:message]) unless value.to_s =~ configuration[:with]
|
693
|
+
end
|
694
|
+
end
|
695
|
+
|
696
|
+
# Validates whether the value of the specified attribute is available in a particular enumerable object.
|
697
|
+
#
|
698
|
+
# class Person < ActiveRecord::Base
|
699
|
+
# validates_inclusion_of :gender, :in => %w( m f ), :message => "woah! what are you then!??!!"
|
700
|
+
# validates_inclusion_of :age, :in => 0..99
|
701
|
+
# validates_inclusion_of :format, :in => %w( jpg gif png ), :message => "extension %s is not included in the list"
|
702
|
+
# end
|
703
|
+
#
|
704
|
+
# Configuration options:
|
705
|
+
# * <tt>in</tt> - An enumerable object of available items
|
706
|
+
# * <tt>message</tt> - Specifies a customer error message (default is: "is not included in the list")
|
707
|
+
# * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
|
708
|
+
# * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
|
709
|
+
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
710
|
+
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
|
711
|
+
# method, proc or string should return or evaluate to a true or false value.
|
712
|
+
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
713
|
+
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
|
714
|
+
# method, proc or string should return or evaluate to a true or false value.
|
715
|
+
def validates_inclusion_of(*attr_names)
|
716
|
+
configuration = { :message => ActiveRecord::Errors.default_error_messages[:inclusion], :on => :save }
|
717
|
+
configuration.update(attr_names.extract_options!)
|
718
|
+
|
719
|
+
enum = configuration[:in] || configuration[:within]
|
720
|
+
|
721
|
+
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?")
|
722
|
+
|
723
|
+
validates_each(attr_names, configuration) do |record, attr_name, value|
|
724
|
+
record.errors.add(attr_name, configuration[:message] % value) unless enum.include?(value)
|
725
|
+
end
|
726
|
+
end
|
727
|
+
|
728
|
+
# Validates that the value of the specified attribute is not in a particular enumerable object.
|
729
|
+
#
|
730
|
+
# class Person < ActiveRecord::Base
|
731
|
+
# validates_exclusion_of :username, :in => %w( admin superuser ), :message => "You don't belong here"
|
732
|
+
# validates_exclusion_of :age, :in => 30..60, :message => "This site is only for under 30 and over 60"
|
733
|
+
# validates_exclusion_of :format, :in => %w( mov avi ), :message => "extension %s is not allowed"
|
734
|
+
# end
|
735
|
+
#
|
736
|
+
# Configuration options:
|
737
|
+
# * <tt>in</tt> - An enumerable object of items that the value shouldn't be part of
|
738
|
+
# * <tt>message</tt> - Specifies a customer error message (default is: "is reserved")
|
739
|
+
# * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
|
740
|
+
# * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
|
741
|
+
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
742
|
+
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
|
743
|
+
# method, proc or string should return or evaluate to a true or false value.
|
744
|
+
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
745
|
+
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
|
746
|
+
# method, proc or string should return or evaluate to a true or false value.
|
747
|
+
def validates_exclusion_of(*attr_names)
|
748
|
+
configuration = { :message => ActiveRecord::Errors.default_error_messages[:exclusion], :on => :save }
|
749
|
+
configuration.update(attr_names.extract_options!)
|
750
|
+
|
751
|
+
enum = configuration[:in] || configuration[:within]
|
752
|
+
|
753
|
+
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?")
|
754
|
+
|
755
|
+
validates_each(attr_names, configuration) do |record, attr_name, value|
|
756
|
+
record.errors.add(attr_name, configuration[:message] % value) if enum.include?(value)
|
757
|
+
end
|
758
|
+
end
|
759
|
+
|
760
|
+
# Validates whether the associated object or objects are all valid themselves. Works with any kind of association.
|
761
|
+
#
|
762
|
+
# class Book < ActiveRecord::Base
|
763
|
+
# has_many :pages
|
764
|
+
# belongs_to :library
|
765
|
+
#
|
766
|
+
# validates_associated :pages, :library
|
767
|
+
# end
|
768
|
+
#
|
769
|
+
# Warning: If, after the above definition, you then wrote:
|
770
|
+
#
|
771
|
+
# class Page < ActiveRecord::Base
|
772
|
+
# belongs_to :book
|
773
|
+
#
|
774
|
+
# validates_associated :book
|
775
|
+
# end
|
776
|
+
#
|
777
|
+
# ...this would specify a circular dependency and cause infinite recursion.
|
778
|
+
#
|
779
|
+
# NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association
|
780
|
+
# is both present and guaranteed to be valid, you also need to use validates_presence_of.
|
781
|
+
#
|
782
|
+
# Configuration options:
|
783
|
+
# * <tt>message</tt> - A custom error message (default is: "is invalid")
|
784
|
+
# * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
|
785
|
+
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
786
|
+
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
|
787
|
+
# method, proc or string should return or evaluate to a true or false value.
|
788
|
+
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
789
|
+
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
|
790
|
+
# method, proc or string should return or evaluate to a true or false value.
|
791
|
+
def validates_associated(*attr_names)
|
792
|
+
configuration = { :message => ActiveRecord::Errors.default_error_messages[:invalid], :on => :save }
|
793
|
+
configuration.update(attr_names.extract_options!)
|
794
|
+
|
795
|
+
validates_each(attr_names, configuration) do |record, attr_name, value|
|
796
|
+
record.errors.add(attr_name, configuration[:message]) unless
|
797
|
+
(value.is_a?(Array) ? value : [value]).inject(true) { |v, r| (r.nil? || r.valid?) && v }
|
798
|
+
end
|
799
|
+
end
|
800
|
+
|
801
|
+
# Validates whether the value of the specified attribute is numeric by trying to convert it to
|
802
|
+
# a float with Kernel.Float (if <tt>integer</tt> is false) or applying it to the regular expression
|
803
|
+
# <tt>/\A[\+\-]?\d+\Z/</tt> (if <tt>integer</tt> is set to true).
|
804
|
+
#
|
805
|
+
# class Person < ActiveRecord::Base
|
806
|
+
# validates_numericality_of :value, :on => :create
|
807
|
+
# end
|
808
|
+
#
|
809
|
+
# Configuration options:
|
810
|
+
# * <tt>message</tt> - A custom error message (default is: "is not a number")
|
811
|
+
# * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
|
812
|
+
# * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false)
|
813
|
+
# * <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
|
814
|
+
# * <tt>greater_than</tt> Specifies the value must be greater than the supplied value
|
815
|
+
# * <tt>greater_than_or_equal_to</tt> Specifies the value must be greater than or equal the supplied value
|
816
|
+
# * <tt>equal_to</tt> Specifies the value must be equal to the supplied value
|
817
|
+
# * <tt>less_than</tt> Specifies the value must be less than the supplied value
|
818
|
+
# * <tt>less_than_or_equal_to</tt> Specifies the value must be less than or equal the supplied value
|
819
|
+
# * <tt>odd</tt> Specifies the value must be an odd number
|
820
|
+
# * <tt>even</tt> Specifies the value must be an even number
|
821
|
+
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
822
|
+
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
|
823
|
+
# method, proc or string should return or evaluate to a true or false value.
|
824
|
+
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
825
|
+
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
|
826
|
+
# method, proc or string should return or evaluate to a true or false value.
|
827
|
+
def validates_numericality_of(*attr_names)
|
828
|
+
configuration = { :on => :save, :only_integer => false, :allow_nil => false }
|
829
|
+
configuration.update(attr_names.extract_options!)
|
830
|
+
|
831
|
+
|
832
|
+
numericality_options = ALL_NUMERICALITY_CHECKS.keys & configuration.keys
|
833
|
+
|
834
|
+
(numericality_options - [ :odd, :even ]).each do |option|
|
835
|
+
raise ArgumentError, ":#{option} must be a number" unless configuration[option].is_a?(Numeric)
|
836
|
+
end
|
837
|
+
|
838
|
+
validates_each(attr_names,configuration) do |record, attr_name, value|
|
839
|
+
raw_value = record.send("#{attr_name}_before_type_cast") || value
|
840
|
+
|
841
|
+
next if configuration[:allow_nil] and raw_value.nil?
|
842
|
+
|
843
|
+
if configuration[:only_integer]
|
844
|
+
unless raw_value.to_s =~ /\A[+-]?\d+\Z/
|
845
|
+
record.errors.add(attr_name, configuration[:message] || ActiveRecord::Errors.default_error_messages[:not_a_number])
|
846
|
+
next
|
847
|
+
end
|
848
|
+
raw_value = raw_value.to_i
|
849
|
+
else
|
850
|
+
begin
|
851
|
+
raw_value = Kernel.Float(raw_value.to_s)
|
852
|
+
rescue ArgumentError, TypeError
|
853
|
+
record.errors.add(attr_name, configuration[:message] || ActiveRecord::Errors.default_error_messages[:not_a_number])
|
854
|
+
next
|
855
|
+
end
|
856
|
+
end
|
857
|
+
|
858
|
+
numericality_options.each do |option|
|
859
|
+
case option
|
860
|
+
when :odd, :even
|
861
|
+
record.errors.add(attr_name, configuration[:message] || ActiveRecord::Errors.default_error_messages[option]) unless raw_value.to_i.method(ALL_NUMERICALITY_CHECKS[option])[]
|
862
|
+
else
|
863
|
+
record.errors.add(attr_name, configuration[:message] || (ActiveRecord::Errors.default_error_messages[option] % configuration[option])) unless raw_value.method(ALL_NUMERICALITY_CHECKS[option])[configuration[option]]
|
864
|
+
end
|
865
|
+
end
|
866
|
+
end
|
867
|
+
end
|
868
|
+
|
869
|
+
# Creates an object just like Base.create but calls save! instead of save
|
870
|
+
# so an exception is raised if the record is invalid.
|
871
|
+
def create!(attributes = nil)
|
872
|
+
if attributes.is_a?(Array)
|
873
|
+
attributes.collect { |attr| create!(attr) }
|
874
|
+
else
|
875
|
+
object = new(attributes)
|
876
|
+
object.save!
|
877
|
+
object
|
878
|
+
end
|
879
|
+
end
|
880
|
+
|
881
|
+
|
882
|
+
private
|
883
|
+
def write_inheritable_set(key, methods)
|
884
|
+
existing_methods = read_inheritable_attribute(key) || []
|
885
|
+
write_inheritable_attribute(key, existing_methods | methods)
|
886
|
+
end
|
887
|
+
|
888
|
+
def validation_method(on)
|
889
|
+
case on
|
890
|
+
when :save then :validate
|
891
|
+
when :create then :validate_on_create
|
892
|
+
when :update then :validate_on_update
|
893
|
+
end
|
894
|
+
end
|
50
895
|
end
|
51
896
|
|
52
897
|
# The validation process on save can be skipped by passing false. The regular Base#save method is
|
53
898
|
# replaced with this when the validations module is mixed in, which it is by default.
|
54
899
|
def save_with_validation(perform_validation = true)
|
55
|
-
if perform_validation && valid? || !perform_validation
|
900
|
+
if perform_validation && valid? || !perform_validation
|
901
|
+
save_without_validation
|
902
|
+
else
|
903
|
+
false
|
904
|
+
end
|
905
|
+
end
|
906
|
+
|
907
|
+
# Attempts to save the record just like Base#save but will raise a RecordInvalid exception instead of returning false
|
908
|
+
# if the record is not valid.
|
909
|
+
def save_with_validation!
|
910
|
+
if valid?
|
911
|
+
save_without_validation!
|
912
|
+
else
|
913
|
+
raise RecordInvalid.new(self)
|
914
|
+
end
|
56
915
|
end
|
57
916
|
|
58
917
|
# Updates a single attribute and saves the record without going through the normal validation procedure.
|
59
918
|
# This is especially useful for boolean flags on existing records. The regular +update_attribute+ method
|
60
919
|
# in Base is replaced with this when the validations module is mixed in, which it is by default.
|
61
920
|
def update_attribute_with_validation_skipping(name, value)
|
62
|
-
|
921
|
+
send(name.to_s + '=', value)
|
63
922
|
save(false)
|
64
923
|
end
|
65
924
|
|
66
925
|
# Runs validate and validate_on_create or validate_on_update and returns true if no errors were added otherwise false.
|
67
926
|
def valid?
|
68
927
|
errors.clear
|
928
|
+
|
929
|
+
run_validations(:validate)
|
69
930
|
validate
|
70
|
-
|
931
|
+
|
932
|
+
if new_record?
|
933
|
+
run_validations(:validate_on_create)
|
934
|
+
validate_on_create
|
935
|
+
else
|
936
|
+
run_validations(:validate_on_update)
|
937
|
+
validate_on_update
|
938
|
+
end
|
939
|
+
|
71
940
|
errors.empty?
|
72
941
|
end
|
73
942
|
|
74
943
|
# Returns the Errors object that holds all information about attribute error messages.
|
75
944
|
def errors
|
76
|
-
@errors
|
77
|
-
@errors
|
945
|
+
@errors ||= Errors.new(self)
|
78
946
|
end
|
79
947
|
|
80
948
|
protected
|
81
949
|
# Overwrite this method for validation checks on all saves and use Errors.add(field, msg) for invalid attributes.
|
82
950
|
def validate #:doc:
|
83
|
-
end
|
951
|
+
end
|
84
952
|
|
85
953
|
# Overwrite this method for validation checks used only on creation.
|
86
954
|
def validate_on_create #:doc:
|
@@ -89,117 +957,36 @@ module ActiveRecord
|
|
89
957
|
# Overwrite this method for validation checks used only on updates.
|
90
958
|
def validate_on_update # :doc:
|
91
959
|
end
|
92
|
-
end
|
93
|
-
|
94
|
-
# Active Record validation is reported to and from this object, which is used by Base#save to
|
95
|
-
# determine whether the object in a valid state to be saved. See usage example in Validations.
|
96
|
-
class Errors
|
97
|
-
def initialize(base) # :nodoc:
|
98
|
-
@base, @errors = base, {}
|
99
|
-
end
|
100
|
-
|
101
|
-
# Adds an error to the base object instead of any particular attribute. This is used
|
102
|
-
# to report errors that doesn't tie to any specific attribute, but rather to the object
|
103
|
-
# as a whole. These error messages doesn't get prepended with any field name when iterating
|
104
|
-
# with each_full, so they should be complete sentences.
|
105
|
-
def add_to_base(msg)
|
106
|
-
add(:base, msg)
|
107
|
-
end
|
108
|
-
|
109
|
-
# Adds an error message (+msg+) to the +attribute+, which will be returned on a call to <tt>on(attribute)</tt>
|
110
|
-
# for the same attribute and ensure that this error object returns false when asked if +empty?+. More than one
|
111
|
-
# error can be added to the same +attribute+ in which case an array will be returned on a call to <tt>on(attribute)</tt>.
|
112
|
-
# If no +msg+ is supplied, "invalid" is assumed.
|
113
|
-
def add(attribute, msg = "invalid")
|
114
|
-
@errors[attribute] = [] if @errors[attribute].nil?
|
115
|
-
@errors[attribute] << msg
|
116
|
-
end
|
117
|
-
|
118
|
-
# Will add an error message to each of the attributes in +attributes+ that is empty (defined by <tt>attribute_present?</tt>).
|
119
|
-
def add_on_empty(attributes, msg = "can't be empty")
|
120
|
-
[attributes].flatten.each { |attr| add(attr, msg) unless @base.attribute_present?(attr) }
|
121
|
-
end
|
122
|
-
|
123
|
-
# Will add an error message to each of the attributes in +attributes+ that has a length outside of the passed boundary +range+.
|
124
|
-
# If the length is above the boundary, the too_long_msg message will be used. If below, the too_short_msg.
|
125
|
-
def add_on_boundary_breaking(attributes, range, too_long_msg = "is too long (max is %d characters)", too_short_msg = "is too short (min is %d characters)")
|
126
|
-
for attr in [attributes].flatten
|
127
|
-
add(attr, too_short_msg % range.begin) if @base.attribute_present?(attr) && @base.send(attr).length < range.begin
|
128
|
-
add(attr, too_long_msg % range.end) if @base.attribute_present?(attr) && @base.send(attr).length > range.end
|
129
|
-
end
|
130
|
-
end
|
131
|
-
|
132
|
-
alias :add_on_boundry_breaking :add_on_boundary_breaking
|
133
|
-
|
134
|
-
# Returns true if the specified +attribute+ has errors associated with it.
|
135
|
-
def invalid?(attribute)
|
136
|
-
!@errors[attribute].nil?
|
137
|
-
end
|
138
|
-
|
139
|
-
# * Returns nil, if no errors are associated with the specified +attribute+.
|
140
|
-
# * Returns the error message, if one error is associated with the specified +attribute+.
|
141
|
-
# * Returns an array of error messages, if more than one error is associated with the specified +attribute+.
|
142
|
-
def on(attribute)
|
143
|
-
if @errors[attribute].nil?
|
144
|
-
nil
|
145
|
-
elsif @errors[attribute].length == 1
|
146
|
-
@errors[attribute].first
|
147
|
-
else
|
148
|
-
@errors[attribute]
|
149
|
-
end
|
150
|
-
end
|
151
|
-
|
152
|
-
alias :[] :on
|
153
|
-
|
154
|
-
# Returns errors assigned to base object through add_to_base according to the normal rules of on(attribute).
|
155
|
-
def on_base
|
156
|
-
on(:base)
|
157
|
-
end
|
158
|
-
|
159
|
-
# Yields each attribute and associated message per error added.
|
160
|
-
def each
|
161
|
-
@errors.each_key { |attr| @errors[attr].each { |msg| yield attr, msg } }
|
162
|
-
end
|
163
|
-
|
164
|
-
# Yields each full error message added. So Person.errors.add("first_name", "can't be empty") will be returned
|
165
|
-
# through iteration as "First name can't be empty".
|
166
|
-
def each_full
|
167
|
-
full_messages.each { |msg| yield msg }
|
168
|
-
end
|
169
960
|
|
170
|
-
|
171
|
-
|
172
|
-
|
173
|
-
|
174
|
-
|
175
|
-
|
176
|
-
|
177
|
-
|
961
|
+
private
|
962
|
+
def run_validations(validation_method)
|
963
|
+
validations = self.class.read_inheritable_attribute(validation_method.to_sym)
|
964
|
+
if validations.nil? then return end
|
965
|
+
validations.each do |validation|
|
966
|
+
if validation.is_a?(Symbol)
|
967
|
+
self.send(validation)
|
968
|
+
elsif validation.is_a?(String)
|
969
|
+
eval(validation, binding)
|
970
|
+
elsif validation_block?(validation)
|
971
|
+
validation.call(self)
|
972
|
+
elsif validation_class?(validation, validation_method)
|
973
|
+
validation.send(validation_method, self)
|
178
974
|
else
|
179
|
-
|
975
|
+
raise(
|
976
|
+
ActiveRecordError,
|
977
|
+
"Validations need to be either a symbol, string (to be eval'ed), proc/method, or " +
|
978
|
+
"class implementing a static validation method"
|
979
|
+
)
|
180
980
|
end
|
181
981
|
end
|
182
982
|
end
|
183
|
-
|
184
|
-
return full_messages
|
185
|
-
end
|
186
983
|
|
187
|
-
|
188
|
-
|
189
|
-
|
190
|
-
|
191
|
-
|
192
|
-
|
193
|
-
|
194
|
-
@errors = {}
|
195
|
-
end
|
196
|
-
|
197
|
-
# Returns the total number of errors added. Two errors added to the same attribute will be counted as such
|
198
|
-
# with this as well.
|
199
|
-
def count
|
200
|
-
error_count = 0
|
201
|
-
@errors.each_value { |attribute| error_count += attribute.length }
|
202
|
-
error_count
|
203
|
-
end
|
984
|
+
def validation_block?(validation)
|
985
|
+
validation.respond_to?("call") && (validation.arity == 1 || validation.arity == -1)
|
986
|
+
end
|
987
|
+
|
988
|
+
def validation_class?(validation, validation_method)
|
989
|
+
validation.respond_to?(validation_method)
|
990
|
+
end
|
204
991
|
end
|
205
992
|
end
|