Sylar Sylar - 3 months ago 10x
Ruby Question

Hash Table Column Values as Integer

I have followed this tutorial to have a hash column on my model which works great.

When I work out codes in the

rails console
, it becomes different within my controller code. In the console:

Foo.update_attributes(bar: {"a" => 1, "b" => 2})

My values are shown as an integer, in the console. In my controller, if I'm doing calculations, I have to add
and it becomes messy. My values will forever be a number. Can I simple add an int or float for the column?

add_column :foos, :bar, :hstore, :integer, default: {}, null: false

The above does not work.


You can use a hook on your model:

before_save -> r {{|k, v|[k] = v.to_i} }