diff options
author | Sean Griffin <sean@thoughtbot.com> | 2015-01-23 14:22:53 -0700 |
---|---|---|
committer | Sean Griffin <sean@thoughtbot.com> | 2015-01-23 14:30:23 -0700 |
commit | 7c6f3938dee47f0932c2a1d4924adaebc25517ac (patch) | |
tree | 89ce24319bf2159209fba8faefc4b80dafaee894 /activerecord/lib | |
parent | 96e504ec8af149962312c13dd418e13e4c74ce86 (diff) | |
download | rails-7c6f3938dee47f0932c2a1d4924adaebc25517ac.tar.gz rails-7c6f3938dee47f0932c2a1d4924adaebc25517ac.tar.bz2 rails-7c6f3938dee47f0932c2a1d4924adaebc25517ac.zip |
Move integer range validation to never raise on assignment
Given that this was originally added to normalize an error that would
have otherwise come from the database (inconsistently), it's more
natural for us to raise in `type_cast_for_database`, rather than
`type_cast_from_user`. This way, things like numericality validators can
handle it instead if the user chooses to do so. It also fixes an issue
where assigning an out of range value would make it impossible to assign
a new value later.
This fixes several vague issues, none of which were ever directly
reported, so I have no issue number to give. Places it was mentioned
which I can remember:
- https://github.com/thoughtbot/shoulda-matchers/blob/9ba21381d7caf045053a81f32df7de2f49687820/lib/shoulda/matchers/active_model/allow_value_matcher.rb#L261-L263
- https://github.com/rails/rails/issues/18653#issuecomment-71197026
Diffstat (limited to 'activerecord/lib')
-rw-r--r-- | activerecord/lib/active_record/type/integer.rb | 14 |
1 files changed, 9 insertions, 5 deletions
diff --git a/activerecord/lib/active_record/type/integer.rb b/activerecord/lib/active_record/type/integer.rb index 394fe008f9..90ca9f88da 100644 --- a/activerecord/lib/active_record/type/integer.rb +++ b/activerecord/lib/active_record/type/integer.rb @@ -16,13 +16,19 @@ module ActiveRecord :integer end - alias type_cast_for_database type_cast - def type_cast_from_database(value) return if value.nil? value.to_i end + def type_cast_for_database(value) + result = type_cast(value) + if result + ensure_in_range(result) + end + result + end + protected attr_reader :range @@ -34,9 +40,7 @@ module ActiveRecord when true then 1 when false then 0 else - result = value.to_i rescue nil - ensure_in_range(result) if result - result + value.to_i rescue nil end end |