Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RangeError for simple integer assignment in Rails 4.2.0 that should be caught by validation

* UPDATE: this is now fixed in 4.2.stable and 4.2.1 *

in Rails 4.2.0 (and current 4.2.stable), the ensure_in_range method happens before AR validation, yielding a RangeError

if I do something as simple as

@obj.threshold = 10_000_000_000

on a column with a postgres type integer

 threshold  | integer                     | 

it yields

RangeError: 10000000000 is out of range for ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Integer with limit 4 from .../2.0.0-p598/lib/ruby/gems/2.0.0/bundler/gems/rails-62e9e61f2d1b/activerecord/lib/active_record/type/integer.rb:41:in `ensure_in_range'

which is true! but tell that to the users. there's an ActiveRecord model validation like

  validates :threshold,  presence: true,
    numericality: { greater_than_or_equal_to: 0, less_than: 1_000_000}

i can't imagine this is expected behavior, anyone have any explanation why this type cast happens before validation?

like image 433
whatbird Avatar asked Jan 22 '15 17:01

whatbird


2 Answers

Get the latest rails version to fix this error, it was recently fixed by Sean Griffin

To do that before a version comes out, remove the specific version in your gemfile and use the git location hint :

gem 'rails', :git => 'https://github.com/rails/rails.git'
like image 109
jazzytomato Avatar answered Oct 03 '22 09:10

jazzytomato


You can force your migration file to use a BigInt. I had the same problem but I am not using Rails but just ActiveRecord. This will solve your bug:

t.integer :really_big_int, limit: 8

like image 35
Fran Martinez Avatar answered Oct 03 '22 09:10

Fran Martinez