我在PostGres 9.5中使用Rails 4.2.7。我在Rails迁移中有这个专栏......
my_num | integer |
在我的模型中,我想筛选太大的数字并将它们设置为零。例如,我的模型上设置了数字“659722222222222”并导致以下错误
Error during processing: (RangeError) 659722222222222 is out of range for ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Integer with limit 4
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/type/integer.rb:45:in `ensure_in_range'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/type/integer.rb:23:in `type_cast_for_database'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/quoting.rb:13:in `quote'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:641:in `block (2 levels) in values_sql_for_columns_and_attributes'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:631:in `each'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:631:in `each_with_index'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:631:in `each'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:631:in `map'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:631:in `block in values_sql_for_columns_and_attributes'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:630:in `map'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:630:in `values_sql_for_columns_and_attributes'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:530:in `import_without_validations_or_callbacks'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:490:in `import_with_validations'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:417:in `import_helper'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:331:in `import'
/Users/davea/Documents/workspace//app/services/abstract_import_service.rb:161:in `block in save_my_object__time_results'
除了保存模型之外,我想将字段设置为nil,只要它设置为对PostGres SQL来说太大的整数值。我该怎么做?
注意,我不想更改PostGres列的列类型。你不觉得这会那么容易,是吗?
答案 0 :(得分:2)
2147483647
是Postgres中整数类型的最大值。
before_save :is_too_big
def is_too_big
if my_num > 2147483647
# do something
end
end
如果你不想在代码中添加魔术数字,我建议你在超出范围时抓住一个例外:
# somewhere in the code
u = User.new(my_num: 2147483648)
begin
u.save
rescue RangeError => e
u.my_num = nil
u.save
end
答案 1 :(得分:0)
添加验证前事件
before_validation :ensure_my_num_ok
并设置值,如果它不好
def ensure_my_num_ok
self.my_num = nil if my_num > 100000000
end