Ruby on Rails Sunday, April 27, 2014

On 27 April 2014 06:38, tekram <tashfeen.ekram@gmail.com> wrote:
> I have set my float id's. I have a Rails 3.0 app and using a MySQL database.
> It seemed to work fine on a Postgres database.
>
> Here is my problem:
>
> irb(main):033:0> Patient.first
>
> Patient Load (1.3ms) SELECT `patients`.* FROM `patients` LIMIT 1
>
> => #<Patient pid: 29312000.0, created_at: "2014-04-25 19:05:10", updated_at:
> "2014-04-25 19:05:10", race: "WHITE", ethnicity: "NOT HISPANIC", age: 47>
>
> irb(main):034:0> Patient.find_by_pid(Patient.first.pid)
>
> Patient Load (1.1ms) SELECT `patients`.* FROM `patients` LIMIT 1
>
> Patient Load (346.1ms) SELECT `patients`.* FROM `patients` WHERE
> `patients`.`pid` = 29312000.0 LIMIT 1
>
> => nil
>
>
> Basically, I can not use where I have used Float as a part of an Active
> Record Query. Another similar problem on another model.

One of the fundamental rules of floating point numbers is that you
should never normally test for exact equality between them, even if
you believe they have been set to the same value. For example you
cannot guarantee that the value in the db is held to the same
precision as that in memory, so even writing it to the db and reading
it back can change its value.

In addition it is nearly always a bad idea to override the default
Rails id scheme, unless you have a very good reason. Let Rails set
the id and have another field for your float value (if it really needs
to be a float), but even then you will not be able to test for exact
equality. Perhaps you can use a scaled integer type instead.

Colin

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/CAL%3D0gLtSB0pc88QBMU_xkE%3DRshfpMNnhrLJ%3DURRHWf_GfBsZ9w%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment