Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using infinite floats in Ruby on Rails

In a Rails application using SQLite3 I'd like to use the float values Float::INFINITY and -Float::INFINITY in a model with a floating point attribute. Running INSERT queries using Model.create! this seems to work fine, since activerecord uses prepared statements in this case. However, when I try to update a record using foo.save, activerecord doesn't use a prepared stament and just puts the string Infinity right in the query, resulting in

SQLite3::SQLException: no such column: Infinity

Is there a way to work around this or do I need to resort to using strings in model/database?

Rails version 3.2.21, SQLite3 version 1.3.10


Edit. For now I changed the column type to string in the database migration and use

serialize :property, Float

to tell activerecord to store YAML-serialized floats in the database, allowing to store Float::INFINITY just fine.

like image 646
Christoph Avatar asked May 31 '15 19:05

Christoph


People also ask

How do you express infinity in Ruby?

What is infinity in Ruby? It's something that has a starting point but no ending. In Ruby, we can express this concept of infinity with the Float::INFINITY constant.

Does Ruby have floats?

In other words, a float in a Ruby program is a number that contains a decimal point. Ruby will consider any number written without decimals as an integer (as in 138 ) and any number written with decimals as a float (as in 138.0 ).

How do you make a float in Ruby?

The to_f function in Ruby converts the value of the number as a float. If it does not fit in float, then it returns infinity. Parameter: The function takes the integer which is to be converted to float.

What is Nan in Ruby?

Ruby Float nan?() method with example 'Not A Number' means an invalid IEEE floating-point number. Syntax: float.nan?() Parameter: float value to be passed. Return: Return true – if the value is 'not a number' otherwise return false.


1 Answers

It's because Float::INFINITY in rails is defined as 1.0/0, that sqlite3 doesn't know what to do with it. You can use a very big number to define infinity like 9e999 as a replacement to the value you'll be saving to the database

like image 190
Jason Adrian Bargas Avatar answered Oct 21 '22 04:10

Jason Adrian Bargas