ruby - Rails+Postgres - hstore automatic conversion of strings -
i'm using hstore on 1 of models store hash float values. need periodically access , perform calculations values in store.
my current solution working these values convert them float everywhere access them, un-dry. there way me modify store_accessor method automatically covert values read store floats?
i know can specific keys writing function them as described in docs have long list of possible keys, way not dry.
i havent used hstore before, studied documentation provided in question. well, hstore looks useful (too bad available in postgresql db, learned new).
from reading documentation,
note - if using postgresql specific columns hstore or json there no need serialization provided store. utilize store_accessor instead generate accessor methods. aware these columns utilize string keyed hash , not allow access using symbol.
also:
the stored attribute names can retrieved using stored_attributes.
user.stored_attributes[:settings] # [:color, :homepage]
so, getting seperate fields in stored_attribute using stored_attributes hash , getting fields declared on stored_attribute array. now, need override accessors elements in array. can utilize define_method dynamically override accessors. came with.
class workingbill < activerecord::base store_accessor :prices, :cost_price, :selling_price stored_attributes[:prices].each |price_column_name| define_method("#{key}=") |value| super(value.to_f) end define_method(key) super.to_f end end end i havent tested code dont have development environment right now. also, have uncertainty whether super phone call work within define_method. so, seek out. test 1 time development environment.
also, @vakily commented, gem https://github.com/jalkoby/active_store_accessor seems improve , handles boolean, integer fields also.
ruby-on-rails ruby ruby-on-rails-4 hstore postgresql-9.3
No comments:
Post a Comment