Sunday, 15 August 2010

Need to convert a Boolean from Postgres (== String) to a Ruby Boolean -



Need to convert a Boolean from Postgres (== String) to a Ruby Boolean -

i'm using postgres rails. there's query subselect returns boolean, postgres returns string 't' or 'f'. in generated json need real boolean.

this query:

select *, exists ( select true measurement bring together experiment on measurement.experiment_id = experiment.id bring together location on experiment.location_id = location.id location.map_id = map.id limit 1 ) measurements_exist "map"

it doesn't matter whether utilize then true or then 1 or then 'true', string. json response that:

[ {"id":8, ..., "measurements_exist":"f"}, {"id":9, ..., "measurements_exist":"t"} ]

but should(!) that:

[ {"id":8, ..., "measurements_exist":false}, {"id":9, ..., "measurements_exist":true} ]

is there way working right?

thank you!

the solution:

just give corresponding model (here: map) attribute accessor, uses value_as_boolean convert value. every time controller tries access value, uses attribute accessor method automatically.

the controller code:

class mapscontroller < applicationcontroller def index select = ["*"] select.push(measurements_exist) # insert string returned 'measurements_exist' method maps = map.select(select) # results in 'select *, exists (...) measurements_exist "map"' render json: maps end private def measurements_exist "exists ( select true measurement bring together experiment on measurement.experiment_id = experiment.id bring together location on experiment.location_id = location.id location.map_id = map.id limit 1 ) measurements_exist" end end

the model code:

class map < activerecord::base def measurements_exist activerecord::connectionadapters::column.value_to_boolean(self[:measurements_exist]) end end

resulting json:

[ {"id":7, ..., "measurements_exist":false}, {"id":6, ..., "measurements_exist":true} ]

activerecord has method called activerecord::connectionadapters::column.value_to_boolean uses internally convert true-like value ruby true value.

you can utilize in code.

ruby-on-rails ruby-on-rails-3 postgresql ruby-on-rails-3.2 rails-activerecord

No comments:

Post a Comment