ActiveRecord Type issue -- What am I missing?

Hey everyone,

First, apologies for the crosspost, I meant to post this to this
group, my previous post was a mistake.

I’m having a frustrating ActiveRecord issue. Maybe what I’m trying to
do will not work, but if that’s the case, I’d like to know why.
Otherwise I’d love to know what I’m doing wrong.

My goal is to store prices (numbers with exactly two decimal places,
always) in the db as INTs to save space and avoid precision errors.
I’ve done this in PHP with no problem – just store the actual value
*
100, and always divide by 100 when reading from the db. Should be
simple…

I set up a callback based on the “Encrypter” example in the excellent
Agile Web Dev w/ rails book. Callback is as follows:

def after_save(model)
@attrs_to_manage.each do |attr|
res = model[attr[0]].to_f / (10.0**attr[1])
model[attr[0]] = res
RAILS_DEFAULT_LOGGER.info " Result: #{model[attr[0]].inspect}
(class=#{model[attr[0]].class}, model=#{model.inspect})"
end
end

I tried that thinking I was all set. I am puzzled by the result. The
number I expected to see was 12.34. Instead I saw just 12. The log
showed:

FixedDbNum: int to float for price: 1234 / (10**2) = 12.34
Result: 12 (class=Fixnum, model=#<Service:0xb6931500
@attributes={“reference”=>“7000”, “modified_at”=>nil,
“billing_frequency”=>“1”, “price”=>12.34,
“billing_frequency_unit”=>"", “id”=>“1”, “setup_fee”=>“9”,
“user_id”=>“1”, “created_at”=>“2007-05-19 11:43:57”,
“service_name”=>“Test”}>)
Rendering within layouts/timesheet

I am stumped. Somehow the attribute refuses to become a Float and
remains as a Fixnum… yet it shows properly in the attributes list.

Did I make some silly mistake or is something else going on here?

TIA.

-Josh

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs