Sylar Sylar - 4 months ago 12
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
.to_i
or
.to_f
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.

Answer

You can use a hook on your model:

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