2

I feel like I'm taking crazy pills here. I have a MySQL-backed ActiveRecord class and a number of the attributes are reported in Rails as type Integer:

Device.last.score.class # returns `Fixnum`

MySQL reports the column being of type decimal(10,0).

What am I missing here? Even tried a call to reset_column_information. Migration looks correct and schema file looks OK too.

Note: this issue wasn't happening in dev, where I'm using SQLite.

Here is my migration:

class AddScoreColumnToDevices < ActiveRecord::Migration
    def change  
        add_column :devices, :score, :decimal
    end
end
5
  • Assuming you have some records in there , what does Device.first.score.class report? (instead of Device.new) Commented Sep 12, 2013 at 19:12
  • Fixnum as well. I was incorrect above, Device.new.score.class actually returns NilClass for obvious reasons. Fixing that now. Commented Sep 12, 2013 at 19:18
  • Can you save a new Device with a float/decimal score? Device.create(score: 11.11)? Commented Sep 12, 2013 at 23:02
  • Also, I would suggest posting your Device model code and the migration you used to create the Device table/score column. Such will help answering your question more quickly... Commented Sep 12, 2013 at 23:03
  • 1
    @CarlosDrew New records have the same issue. I posted the migration above; it's extremely vanilla. I did not include the class definition because I don't even make mention of the :score attribute in it. It's a basic model class that inherits directly from ActiveRecord::Base. Commented Sep 13, 2013 at 16:17

1 Answer 1

6

The migration did it for me! Thank you!

The defaults for a newly migrated :decimal are :precision => 0 and :scale => 0, which will result in a MySQL decimal accepting nothing after the decimal point.

Ruby will see that number, with nothing after the decimal point, as a Fixnum, which is what you are observing.

So, you need to write a new migration to alter the column and give the decimal precision and scale > 0.

change_column :devices, :score, :decimal, :precision => 10, :scale => 10

References:
ActiveRecord ConnectionAdapter TableDefinition #column
decimal precision and scale
old reference on MySQL column<->Ruby datatype mapping

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.